Java-network programming to achieve UDP chat room (local area network)

     **

* The idea of ​​establishing a UDP receiving end.

**
* 1. Establish udp socket service, because it is to receive data, a port number must be specified.
* 2. Create a data package to store the received data. It is convenient to use the method of the data packet object to parse the data.
*3, use the receive method of the socket service to store the received data in the data packet.
*4, Analyze the data in the data packet by the method of data packet.
* 5, close the resource

Receiver code:

public class UDPRece{
    public static void main(String[] args) throws IOException {
        System.out.println("接收端启动......");
        //1,建立udp socket服务。
        DatagramSocket ds = new DatagramSocket(10000);

        while(true){

        //2,创建数据包。
        byte[] buf = new byte[1024];
        DatagramPacket dp = new DatagramPacket(buf,buf.length);

        //3,使用接收方法将数据存储到数据包中。
        ds.receive(dp);//阻塞式的。

        //4,通过数据包对象的方法,解析其中的数据,比如,地址,端口,数据内容。
        String ip = dp.getAddress().getHostAddress();
        int port = dp.getPort();
        String text = new String(dp.getData(),0,dp.getLength());

        System.out.println(ip+":"+port+":"+text);


        }
        //5,关闭资源。
//      ds.close();


    }



}
     **

* Create the sender of UDP transmission.

**
* Idea:
* 1. Establish udp socket service.
* 2. Encapsulate the data to be sent into a data packet.
*3, the data packet is sent out through the socket service of udp.
* 4. Turn off the socket service.

**

Sending code:

**


public class UDPSend {
    
    

    /**
     * @param args
     * @throws IOException 
     */
    public static void main(String[] args) throws IOException {

        System.out.println("发送端启动......");

        //1,udpsocket服务。使用DatagramSocket对象。
        DatagramSocket ds = new DatagramSocket(8888);


//      String str = "udp传输演示";
        BufferedReader bufr = new BufferedReader(new InputStreamReader(System.in));
        String line = null;

        while((line=bufr.readLine())!=null){


            byte[] buf = line.getBytes();
            DatagramPacket dp = 
                    new DatagramPacket(buf,buf.length,InetAddress.getByName("169.254.226.56"),10000);
            ds.send(dp);

            if("886".equals(line))
                break;
        }

        //4,关闭资源。
        ds.close();


    }

}

The above can realize a simple LAN chat program.

**

note:

(1) It is recommended not to use eclipse for programming, but to use the dos window to compile, just open two dos windows.
(2) Pay attention to the situation that the port is occupied

**

Guess you like

Origin blog.csdn.net/yjh_SE007/article/details/78451523