网络编程之UDP

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.关闭资源。

 package myInetaddress;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetAddress;
import java.net.SocketException; import org.junit.Test;
public class MyInetAddress8 {
@Test public void server() throws Exception{
//1.创建套接字
DatagramSocket server = new DatagramSocket(8878);
//定义数据包,用来接收发送的数据包
byte[] b = new byte[1024];
DatagramPacket dp = new DatagramPacket(b,b.length);
//3.接收数据包
server.receive(dp);
//拆包
String str = new String(dp.getData(),0,dp.getLength());
System.out.println(str);
server.close();
}
@Test
public void client() throws Exception{
//
DatagramSocket d = new DatagramSocket();
//
byte[] b = "地哦啊你好的".getBytes();
DatagramPacket dp = new DatagramPacket(b,b.length,InetAddress.getByName("192.168.11.229"),8878);
//
d.send(dp);
d.close();
} }
地哦啊你好的

  

上一篇:Snort - 配置文件


下一篇:Spring学习资料以及配置环境