使用基于UDP的Java Socket编程,完成在线咨询功能: (1)客户向咨询人员咨询。 (2)咨询人员给出回答。 (3)客户和咨询人员可以一直沟通,直到客户发送bye给咨询人员。
时间: 2023-12-10 21:40:11 浏览: 243
好的,这是一个基于UDP的Java Socket编程实现在线咨询的简单示例代码:
服务端代码:
```java
import java.net.*;
public class Server {
public static void main(String[] args) throws Exception {
DatagramSocket serverSocket = new DatagramSocket(9876); // 创建套接字并指定端口号
byte[] receiveData = new byte[1024];
byte[] sendData = new byte[1024];
while (true) {
DatagramPacket receivePacket = new DatagramPacket(receiveData, receiveData.length);
serverSocket.receive(receivePacket); // 接收客户端发送的消息
String message = new String(receivePacket.getData()).trim();
System.out.println("客户端: " + message);
InetAddress clientAddress = receivePacket.getAddress(); // 获取客户端地址
int clientPort = receivePacket.getPort(); // 获取客户端端口号
if (message.equals("bye")) { // 如果客户端发送了bye,则退出循环
break;
}
String response = "感谢您的咨询!"; // 服务器回复消息
sendData = response.getBytes();
DatagramPacket sendPacket = new DatagramPacket(sendData, sendData.length, clientAddress, clientPort);
serverSocket.send(sendPacket); // 发送回复消息给客户端
}
serverSocket.close(); // 关闭套接字
}
}
```
客户端代码:
```java
import java.net.*;
public class Client {
public static void main(String[] args) throws Exception {
DatagramSocket clientSocket = new DatagramSocket(); // 创建套接字,系统会自动分配端口号
InetAddress serverAddress = InetAddress.getByName("localhost"); // 服务器地址
int serverPort = 9876; // 服务器端口号
byte[] sendData = new byte[1024];
byte[] receiveData = new byte[1024];
while (true) {
String message = "咨询问题"; // 客户端发送消息
sendData = message.getBytes();
DatagramPacket sendPacket = new DatagramPacket(sendData, sendData.length, serverAddress, serverPort);
clientSocket.send(sendPacket); // 发送消息给服务器
DatagramPacket receivePacket = new DatagramPacket(receiveData, receiveData.length);
clientSocket.receive(receivePacket); // 接收服务器回复的消息
String response = new String(receivePacket.getData()).trim();
System.out.println("服务器: " + response);
if (response.equals("感谢您的咨询!")) { // 如果服务器回复了感谢消息,则退出循环
break;
}
}
clientSocket.close(); // 关闭套接字
}
}
```
这个示例代码只是一个简单的UDP Socket编程实现,实际应用中还需要考虑更多的因素,比如异常处理、并发处理等。
阅读全文