标签:地址 res system socket exception amp name port 接收
发送消息
//不需要连接服务器
public static void main(String[] args) throws Exception {
//1.建立一个socket
DatagramSocket datagramSocket = new DatagramSocket();
//2.建个包
String msg = "你好";
InetAddress localhost = InetAddress.getByName("localhost");
int port = 9090;
//数据,数据长度起始,发送给谁
DatagramPacket datagramPacket = new DatagramPacket(msg.getBytes(), 0, msg.getBytes().length,localhost,port);
//3.发送包
datagramSocket.send(datagramPacket);
//关闭流
datagramSocket.close();
}
接收端
public static void main(String[] args) throws Exception {
//开放端口
DatagramSocket datagramSocket = new DatagramSocket(9090);
//接受数据包
byte[] bytes = new byte[1024];
DatagramPacket datagramPacket = new DatagramPacket(bytes, 0, bytes.length);
datagramSocket.receive(datagramPacket);
System.out.println(datagramPacket.getAddress().getHostAddress());
System.out.println(new String(datagramPacket.getData(),0,datagramPacket.getLength()));
//关闭连接
datagramSocket.close();
}
标签:地址 res system socket exception amp name port 接收
原文地址:https://www.cnblogs.com/saxonsong/p/14675713.html