【转】javaUDP套接字通信

ⅰ亾dé卋堺 提交于 2021-02-18 01:19:53

 

Java UDP网络编程 - 最简单示例

转自 http://blog.csdn.net/wintys/article/details/3525643


  1. /**
  2. *UDPServer
  3. *@author Winty wintys@gmail.com
  4. *@version 2008-12-15
  5. */
  6. import java.io.*;
  7. import java.net.*;
  8. class UDPServer{
  9. publicstaticvoid main(String[] args)throws IOException{
  10. DatagramSocket server = new DatagramSocket(5050);
  11. byte[] recvBuf = newbyte[100];
  12. DatagramPacket recvPacket
  13. = new DatagramPacket(recvBuf , recvBuf.length);
  14. server.receive(recvPacket);
  15. String recvStr = new String(recvPacket.getData() , 0 , recvPacket.getLength());
  16. System.out.println("Hello World!" + recvStr);
  17. int port = recvPacket.getPort();
  18. InetAddress addr = recvPacket.getAddress();
  19. String sendStr = "Hello ! I'm Server";
  20. byte[] sendBuf;
  21. sendBuf = sendStr.getBytes();
  22. DatagramPacket sendPacket
  23. = new DatagramPacket(sendBuf , sendBuf.length , addr , port );
  24. server.send(sendPacket);
  25. server.close();
  26. }
  27. }

  1. /**
  2. *UDPClient
  3. *@author Winty wintys@gmail.com
  4. *@version 2008-12-15
  5. */
  6. import java.io.*;
  7. import java.net.*;
  8. class UDPClient{
  9. publicstaticvoid main(String[] args)throws IOException{
  10. DatagramSocket client = new DatagramSocket();
  11. String sendStr = "Hello! I'm Client";
  12. byte[] sendBuf;
  13. sendBuf = sendStr.getBytes();
  14. InetAddress addr = InetAddress.getByName("127.0.0.1");
  15. int port = 5050;
  16. DatagramPacket sendPacket
  17. = new DatagramPacket(sendBuf ,sendBuf.length , addr , port);
  18. client.send(sendPacket);
  19. byte[] recvBuf = newbyte[100];
  20. DatagramPacket recvPacket
  21. = new DatagramPacket(recvBuf , recvBuf.length);
  22. client.receive(recvPacket);
  23. String recvStr = new String(recvPacket.getData() , 0 ,recvPacket.getLength());
  24. System.out.println("收到:" + recvStr);
  25. client.close();
  26. }
  27. }
 
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!