Udp网络编程
发送方程序UdpSender.java:
import java.net.*; public class UdpSender { public static void main(String[] args) { /*发送数据包*/ String str = "Hello,you!"; byte buffer[] = str.getBytes(); try { InetAddress address = InetAddress.getByName("127.0.0.1"); DatagramPacket data_pack = new DatagramPacket(buffer,buffer.length,address,666); DatagramSocket mail_data = new DatagramSocket(); while(true) { mail_data.send(data_pack); Thread.sleep(1000); } } catch (Exception e) { } } }
接收方程序UdpReceiver.java:
import java.net.*; public class UdpReceiver { public static void main(String[] args) { /*接受数据包*/ DatagramPacket pack = null; DatagramSocket mail_data = null; byte data[] = new byte[8192]; try { pack = new DatagramPacket(data,data.length); mail_data = new DatagramSocket(666); } catch (Exception e) { } while(true) { if(mail_data == null) break; else try { mail_data.receive(pack); String message = new String(pack.getData(),0,pack.getLength()); System.out.println("Receive message:" + message); } catch (Exception e) { } } } }