欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

Socket通信-UDP-DatagramSocket

程序员文章站 2024-01-31 20:35:34
...

 

使用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();
  }
 }

相关标签: Socket通信