标签:color bytes byte package java.net packet str pre 接收
1 package UDP; 2 3 import java.io.IOException; 4 import java.net.DatagramPacket; 5 import java.net.DatagramSocket; 6 import java.net.InetAddress; 7 import java.net.SocketException; 8 import java.net.UnknownHostException; 9 10 public class Demo1 { 11 12 public static void main(String[] args) throws IOException { 13 14 DatagramSocket socket = new DatagramSocket(); 15 16 String str = "hello"; 17 // 打包封装 18 DatagramPacket packet = new DatagramPacket(str.getBytes(), str.length(), InetAddress.getByName("localhost"), 19 8000); 20 socket.send(packet);// 发送 21 22 // 接收 23 24 byte[] buff = new byte[100]; 25 DatagramPacket packet2 = new DatagramPacket(buff, 100); 26 socket.receive(packet2); 27 System.out.println(new String(buff, 0, packet2.getLength())); 28 socket.close(); 29 } 30 31 }
1 package UDP; 2 3 import java.io.IOException; 4 import java.net.DatagramPacket; 5 import java.net.DatagramSocket; 6 import java.net.InetAddress; 7 import java.net.SocketException; 8 9 public class Demo2 { 10 11 public static void main(String[] args) throws IOException { 12 //接收 13 DatagramSocket socket = new DatagramSocket(8000); 14 byte[] buff = new byte[100]; 15 DatagramPacket packet = new DatagramPacket(buff, 100); 16 socket.receive(packet); 17 System.out.println(new String (buff,0,packet.getLength())); 18 19 //发送 20 String str = "me too"; 21 DatagramPacket packet2 = new DatagramPacket(str.getBytes(), str.length(), packet.getAddress(), 22 packet.getPort()); 23 socket.send(packet2); 24 socket.close(); 25 26 } 27 28 }
标签:color bytes byte package java.net packet str pre 接收
原文地址:http://www.cnblogs.com/the-wang/p/7112272.html