标签:
UDP编程流程:一服务端:1.创建socket。 DatagramSocket socket = new DatagramSocket(8878);
2.创建数据包,用来接收发送的数据包。byte[] b = new byte[1024];DatagramPacket dp = new DatagramPacket(b,0,b.length);
3.接收数据。scoket.recive(dp);
4.关闭资源
二客户端:1.创建socket 。 DatagramSocket socket = new DatagramSocket();
2.数据打包。byte[] b = "地哦啊你好的".getBytes();
DatagramPacket dp = new DatagramPacket(b,b.length,InetAddress.getByName("192.168.11.229"),8878);
3.发送数据。scoket.send(dp)
4.关闭资源。
1 package myInetaddress; 2 import java.net.DatagramPacket; 3 import java.net.DatagramSocket; 4 import java.net.InetAddress; 5 import java.net.SocketException; 6 7 import org.junit.Test; 8 public class MyInetAddress8 { 9 @Test public void server() throws Exception{ 10 //1.创建套接字 11 DatagramSocket server = new DatagramSocket(8878); 12 //定义数据包,用来接收发送的数据包 13 byte[] b = new byte[1024]; 14 DatagramPacket dp = new DatagramPacket(b,b.length); 15 //3.接收数据包 16 server.receive(dp); 17 //拆包 18 String str = new String(dp.getData(),0,dp.getLength()); 19 System.out.println(str); 20 server.close(); 21 } 22 @Test 23 public void client() throws Exception{ 24 //1 25 DatagramSocket d = new DatagramSocket(); 26 //2 27 byte[] b = "地哦啊你好的".getBytes(); 28 DatagramPacket dp = new DatagramPacket(b,b.length,InetAddress.getByName("192.168.11.229"),8878); 29 //3 30 d.send(dp); 31 d.close(); 32 } 33 34 }
地哦啊你好的
标签:
原文地址:http://www.cnblogs.com/huxuebing/p/5765455.html