Socket优化
// 发送方
public class Demo1_SendSocket {
public static void main(String[] args) throws IOException {
Scanner sc = new Scanner(System.in); // 获取键盘输入流
DatagramSocket socket = new DatagramSocket(); // 创建socket对象
while (true) {
String line = sc.nextLine(); // 获取键盘录入
if ("quit".equals(line)) { // 如果输入quit则退出连接
break;
}
DatagramPacket packet = // 创建数据包对象
new DatagramPacket(line.getBytes(), line.getBytes().length, InetAddress.getByName("127.0.0.1"),
6666);
socket.send(packet); // 发送数据包
}
socket.close(); // 关闭socket对象
}
}
// 接收方
public class Demo2_ReceiveSocket {
public static void main(String[] args) throws Exception {
DatagramSocket socket = new DatagramSocket(6666); // 创建socket连接
DatagramPacket packet = new DatagramPacket(new byte[1024], 1024);
while (true) {
socket.receive(packet); // 接收消息
byte[] arr = packet.getData(); // 提取数据
int len = packet.getLength(); // 获取有效字节个数
String ip = packet.getAddress().getHostAddress(); // 获取IP地址
int port = packet.getPort(); // 获取端口号
System.out.println(ip + ":" + port + ":" + new String(arr, 0, len));
}
}
}