网络编程案例1:UDP实现两人通讯聊天

模拟两人实现聊天功能

接受类,代码如下

import java.io.IOException;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetAddress;


public class Recever implements Runnable{

    private DatagramSocket ds;
    public Recever(DatagramSocket ds)
    {
        this.ds = ds;
    }
    @Override
    public void run() {

        while (true){
            byte [] bytes = new byte[1024];
            DatagramPacket packet = new DatagramPacket(bytes,bytes.length);
            //接收,阻塞线程
            try {
                ds.receive(packet);
            } catch (IOException e) {
                e.printStackTrace();
            }
            //包裹上的地址
            InetAddress ip= packet.getAddress();
            String msg = new String(packet.getData(),0,packet.getLength());
            System.out.println("来自:"+ip.getHostName()+"的消息:"+msg);

        }

    }
}

发送类,代码如下:

import java.io.IOException;
import java.net.*;
import java.util.Scanner;

public class Send implements Runnable {

    private DatagramSocket ds ;//发送的数据
    private int recePort;//接收的端口
    private String ipAddress;

    public Send(DatagramSocket ds, int recePort,String ipAddress) {
        this.ds = ds;
        this.recePort = recePort;
        this.ipAddress =ipAddress;
    }

    @Override
    public void run() {
        System.out.println("发送信息:");
        InetAddress ip = null;
        try {
            ip = InetAddress.getByName( ipAddress );
        } catch (UnknownHostException e) {
            e.printStackTrace();
        }

        Scanner in = new Scanner(System.in);

        while (true){
            String str = in.nextLine();
            if(str =="end"){
                break;
            }
            byte[] bytes =str.getBytes();

            DatagramPacket packet = new DatagramPacket(bytes,bytes.length,ip,recePort);
            try {
                ds.send(packet);
            } catch (IOException e) {
                e.printStackTrace();
            }
            ds.close();

        }


    }
}

测试类1:

import java.net.DatagramSocket;
import java.net.SocketException;

public class Man1 {
    public static void main(String[] args) throws SocketException {

        DatagramSocket sendSocket = new DatagramSocket();
        DatagramSocket receSocket = new DatagramSocket(5220);
        new Thread(new Send(sendSocket, 5221,"xxx.xxx.xxx.xxx")).start();//xxx是个人ip地址
        new Thread(new Recever(receSocket)).start();
    }
}

测试类2:

import java.net.DatagramSocket;
import java.net.SocketException;

public class Man2 {
    public static void main(String[] args) throws SocketException {
        DatagramSocket sendSocket = new DatagramSocket();
        DatagramSocket receSocket = new DatagramSocket(5221);
        new Thread(new Send(sendSocket, 5220,"192.168.31.224")).start();
        new Thread(new Recever(receSocket)).start();
    }
}

这就简单的实现了俩个人的消息的发送与接收

你可能感兴趣的:(java基础练习)