Chinaunix首页 | 论坛 | 博客
  • 博客访问: 2534256
  • 博文数量: 245
  • 博客积分: 4125
  • 博客等级: 上校
  • 技术积分: 3113
  • 用 户 组: 普通用户
  • 注册时间: 2009-03-25 23:56
文章分类

全部博文(245)

文章存档

2015年(2)

2014年(26)

2013年(41)

2012年(40)

2011年(134)

2010年(2)

分类: Java

2011-11-13 20:16:29

简单的DatagramSocket demo
  1. import java.io.IOException;
  2. import java.net.DatagramPacket;
  3. import java.net.DatagramSocket;


  4. public class UdpRecv {

  5.     public static void main(String[] args) throws IOException{
  6.         
  7.         DatagramSocket ds = new DatagramSocket(5000);
  8.         byte[] buf = new byte[1024];
  9.         DatagramPacket dp = new DatagramPacket(buf,1024);
  10.         /*
  11.          * Receives a datagram packet from this socket.
  12.          * When this method returns, the DatagramPacket's buffer is filled with the data received.
  13.          * The datagram packet also contains the sender's IP address, and the port number on the sender's machine.
  14.          * This method blocks until a datagram is received.
  15.          */
  16.         ds.receive(dp);
  17.         String userinput = new String(dp.getData(),0,dp.getLength());
  18.         String strRecv = new String(dp.getData(),0,dp.getLength()) + " from "+
  19.         dp.getAddress().getHostAddress()+":"+dp.getPort();
  20.         System.out.println(strRecv);
  21.         ds.close();
  22.         
  23.         
  24.     }

  25. }

  1. import java.io.BufferedReader;
  2. import java.io.IOException;
  3. import java.io.InputStreamReader;
  4. import java.net.DatagramPacket;
  5. import java.net.DatagramSocket;
  6. import java.net.InetAddress;

  7. public class UdpSend {

  8.     public static void main(String[] args) throws IOException{
  9.         while(true){
  10.             DatagramSocket ds = new DatagramSocket();
  11.             String str = "hello socket!";
  12.             BufferedReader userinput = new BufferedReader(new InputStreamReader(System.in));
  13.             str += userinput.readLine();
  14.             DatagramPacket dp = new DatagramPacket(str.getBytes(),str.length(),
  15.                     InetAddress.getByName("127.0.0.1"),5000);
  16.             
  17.             ds.send(dp);
  18.             ds.close();
  19.         }
  20.         
  21.         
  22.     }
  23. }


谢谢访问!

阅读(801) | 评论(0) | 转发(0) |
给主人留下些什么吧!~~