Socket通信-UDP-DatagramSocket

使用DatagramSocket通信(UDP)

//使用udp发送消息
public class UDPMsgSender {
 private static int port = 8000; //需要换一个端口,不能和tcp相同

 public static void send(String msg, InetAddress host){
  if(msg == null)
   return;
  System.out.println("服务端发送消息:"+msg);
  try {
   DatagramSocket socket = new DatagramSocket();
   byte[] buf = msg.getBytes();
   //DatagramPacket packet = new DatagramPacket(buf, buf.length); //java.lang.NullPointerException: null address
   DatagramPacket packet = new DatagramPacket(buf, buf.length, InetAddress.getByName("lenovo-PC"), port);
   socket.send(packet);
   socket.close();
  } catch (IOException e) {
   e.printStackTrace();
  }
 }
}

static class MessageReceiver implements Runnable{
  
  public void run(){
   DatagramSocket socket = null;
   try {
    socket = new DatagramSocket(8000);
    byte[] buf = new byte[1024];
    DatagramPacket packet = new DatagramPacket(buf, buf.length);
    while(true){
     socket.receive(packet);
    
     byte[] msg = packet.getData();
     String msgStr = new String(msg);
     System.out.println("接收服务端的消息:" + msgStr);
    }
   } catch (Exception e) {
    e.printStackTrace();
   }
   socket.close();
  }
 }

猜你喜欢

转载自zw7534313.iteye.com/blog/2420421