UDP通信程序练习
package NetworkProgramming.UDP.Test;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetAddress;
/**
* FileName: SendDemo
* Author: lps
* Date: 2022/4/1 15:42
* Sign:刘品水 Q:1944900433
*/
public class SendDemo {
public static void main(String[] args) throws IOException {
DatagramSocket ds = new DatagramSocket();
InetAddress address = InetAddress.getByName("192.168.10.102");
//DatagramPacket(byte[] buf, int length, InetAddress address, int port)
//指定主机上的指定端口发送数据包的长度 length数据报包结构。
//Scanner sc = new Scanner(System.in);
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
String line;
while ((line = br.readLine()) != null) {
if ("886".equals(line)) {
break;
}
byte[] bys = line.getBytes();
DatagramPacket dp = new DatagramPacket(bys, bys.length, address, 1944);
//SocketException
ds.send(dp);
}
ds.close();
// byte[] bys = input.getBytes(StandardCharsets.UTF_8);
// if ( input == String.valueOf(886)) {
// System.exit(0);
// } else {
// DatagramPacket dp = new DatagramPacket(bys, bys.length, address, 1944);
//
// ds.send(dp);
//
// }
}
}
package NetworkProgramming.UDP.Test;
import java.io.IOException;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
/**
* FileName: ReceiveDemo
* Author: lps
* Date: 2022/4/1 15:42
* Sign:刘品水 Q:1944900433
*/
public class ReceiveDemo {
public static void main(String[] args) throws IOException {
DatagramSocket ds = new DatagramSocket(1944);
//DatagramSocket(int port)
//构建一个数据报套接字绑定到本地主机的指定端口。
while (true){
//DatagramPacket(byte[] buf, int length)
//接收数据包长度 length DatagramPacket构建。
byte[] bys = new byte[1024];
DatagramPacket dp = new DatagramPacket(bys, bys.length);
//void receive(DatagramPacket p)
//接收数据报包从这个插座。
ds.receive(dp);
//System.out.println(dp.toString());
//解析数据包
//byte[] getData()
//返回数据缓冲区。
byte[] data = dp.getData();
//int getLength()
//返回要发送的数据的长度或收到的数据的长度。
int len = dp.getLength();
// String dataString = new String(data,0,len);
// System.out.print("数据是:"+dataString);
System.out.println("接收到的数据是:" + new String(data, 0, len));
}
//ds.close();
}
}