javaUDP协议实现聊天室

发送端


package Socket;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.*;
//UDP传输   发送端
public class UDPSend {
    public static void main(String[] args) throws IOException {
        System.out.println("发送端启动......");

        DatagramSocket datagramSocket  = new DatagramSocket(8888);
        /*String str = "我是发送端  哥们 我来了哈哈哈哈";
        byte [] b = str.getBytes();*/
    BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(System.in));
    String line = null;
    while ((line = bufferedReader.readLine())!=null){

        byte [] b=line.getBytes();
        DatagramPacket datagramPacket = new DatagramPacket(b,b.length,InetAddress.getLocalHost(),10000);
        datagramSocket.send(datagramPacket);
        if("告辞".equals(line))
            break;
    }
        //InetAddress.getByname(“dns解析的地址”)

        datagramSocket.close();
    }
}



接收端


package Socket;

import java.io.IOException;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
//UDP传输   接收端
public class UDPReceive {
//        private static final int timeout =3000;
    public static void main(String[] args) throws IOException {

        System.out.println("接收端启动........");

        DatagramSocket datagramSocket = new DatagramSocket(10000);
        while (true) {
            byte[] b = new byte[1024];

            DatagramPacket datagramPacket = new DatagramPacket(b, b.length);
            datagramSocket.receive(datagramPacket);

            int port = datagramPacket.getPort();
            String ip = datagramPacket.getAddress().getHostAddress();
            String data = new String(datagramPacket.getData(), 0, datagramPacket.getLength());
            System.out.println(port + ip + "\r\n" + data);
           /* System.out.println(new String(b,0,b.length));
            if ("告辞".equals(new String(b,0,b.length)))
                System.out.println(ip+"...退出");*/
        }
    }

}

 

你可能感兴趣的:(UDP协议,java,java)