使用DatagramSocket发送和读取数据

  1. package net.java2000.net;
  2. import java.io.IOException;
  3. import java.net.DatagramPacket;
  4. import java.net.DatagramSocket;
  5. import java.net.InetAddress;
  6. import java.net.SocketException;
  7. /**
  8.  * 使用DatagramPacket和DatagramSocket发送和读取数据。
  9.  * 
  10.  * @author 赵学庆,Java世纪网(java2000.net)
  11.  * 
  12.  */
  13. public class DatagramPacketReceiver {
  14.   public static void main(String[] args) {
  15.     try {
  16.       new DatagramPacketReceiver.DatagramPacketSender().start();
  17.       byte[] inbuf = new byte[256]; // 默认的数据缓冲大小
  18.       DatagramSocket socket = new DatagramSocket(8888);
  19.       // 等待数据
  20.       DatagramPacket packet = new DatagramPacket(inbuf, inbuf.length);
  21.       socket.receive(packet);
  22.       int numBytesReceived = packet.getLength();
  23.       System.out.println(new String(inbuf, 0, numBytesReceived, "UTF-8"));
  24.     } catch (SocketException e) {
  25.       e.printStackTrace();
  26.     } catch (IOException e) {
  27.       e.printStackTrace();
  28.     }
  29.   }
  30.   static class DatagramPacketSender extends Thread {
  31.     public void run() {
  32.       try {
  33.         Thread.sleep(1000); // 休眠1秒,等待接收服务启动
  34.         InetAddress ia = InetAddress.getByName("127.0.0.1");
  35.         byte[] bs = "JAVA世纪网,java2000.net".getBytes("UTF-8");
  36.         DatagramPacket request = new DatagramPacket(bs, bs.length, ia, 8888);
  37.         DatagramSocket socket = new DatagramSocket();
  38.         socket.send(request);
  39.       } catch (Exception e) {
  40.         e.printStackTrace();
  41.       }
  42.     }
  43.   }
  44. }


运行结果
JAVA世纪网,java2000.net


原文: http://www.java2000.net/p9152













<script type="text/javascript"> </script> <script src="http://pagead2.googlesyndication.com/pagead/show_ads.js" type="text/javascript"> </script>

你可能感兴趣的:(JavaScript,java,thread,.net,socket)