JavaUDP协议聊天程序

UDPChatDemo.java


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

public class UDPChatDemo {
   public static void main(String[] args) throws IOException {
      DatagramSocket send = new DatagramSocket();
      Send s = new Send(send);
      DatagramSocket rec = new DatagramSocket(5246);
      Rec r = new Rec(rec);
      new Thread(s).start();
      new Thread(r).start();
   }
}

class Send implements Runnable {
   private DatagramSocket ds;
   public Send(DatagramSocket ds) {
      super();
      this.ds = ds;
   }

   public void run() {
      try {
        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.getLocalHost(), 5246);
           ds.send(dp);
           if ("886".equals(line))
              break;
        }
      } catch (Exception e) {
      }
      ds.close();
   }
}

class Rec implements Runnable {
   private DatagramSocket ds;
   public Rec(DatagramSocket ds) {
      super();
      this.ds = ds;
   }

   public void run() {
      while (true) {
        byte buf[] = new byte[1024];
        DatagramPacket dp = new DatagramPacket(buf, 0, buf.length);
        try {
           ds.receive(dp);
        } catch (IOException e) {
           e.printStackTrace();
        }
        String ip = dp.getAddress().getHostAddress();
         int port = dp.getPort();
        String msg = new String(dp.getData(), 0, dp.getLength());
        System.out.println("ip:" + ip);
        System.out.println("port:" + port);
        System.out.println("massage:" + msg);
        if (msg.equals("886"))
           System.out.println(ip + "退出聊天室");
        System.out.println();
      }
   }
}