在上一篇了解完网络通信德基本概念之后,本章节为了解Tomcat的基本逻辑方便以后对
UDP:(发短信)
发送端:
//不需要连接服务器
public static void main(string[] args)throws Exception {
//1.建立一个socket
DatagramSocket socket=new Datagramsocket();
//2.建个包
String msg ="你好啊,服务器!";
InetAddress localhost = InetAddress.getByName("localhost");
int port = 9090;
// 数据,数据的长度起始,要发送给谁
DatagramPacket, packet = new DatagramPacket(msg.getBytes(), offset: 0, msg.getBytes().length, localhost, port);
//3.发送包
socket.send(packet);
//4.关闭流
socket.close();
接受端:
//开放端口
Datagramsocket socket=new Datagramsocket(9090);
// 接收数据包
byte[ buffer = new byte[1024];
DatagramPacket packet = new DatagramPacket(buffer, 0, buffer.length);
//阻塞接收
socket.receive(packet);
system.out.printin(packet.getAddress().getHostAddress());
System.out.printin(new string(packet.getData(),0,packet.getLength()));
//关闭连接
socket.close();
标签:Datagramsocket,DatagramPacket,socket,Tomcat,packet,msg,new
From: https://www.cnblogs.com/Edehuag/p/18348850