计算机网络聊天程序(分别采用UDP和TCP实现)java代码
时间: 2024-12-10 20:31:58 浏览: 8
在Java中,我们可以使用Socket API来创建基于UDP(用户数据报协议)和TCP(传输控制协议)的网络聊天程序。这里提供一个简化的示例,展示了如何基本地使用这两种协议:
**UDP实现(无连接,不可靠)**:
```java
import java.net.DatagramPacket;
import java.net.DatagramSocket;
public class UDPChatServer {
private DatagramSocket serverSocket;
public void start(int port) throws Exception {
serverSocket = new DatagramSocket(port);
byte[] buffer = new byte[1024];
while (true) {
DatagramPacket packet = new DatagramPacket(buffer, buffer.length);
serverSocket.receive(packet);
String message = new String(packet.getData());
System.out.println("Received message from client: " + message);
}
}
// 这里省略了客户端发送消息的部分,因为UDP是无连接的
}
// UDP客户端类似
public class UDPChatClient {
private DatagramSocket clientSocket;
// 发送消息等操作...
}
```
**TCP实现(面向连接,可靠)**:
```java
import java.io.*;
import java.net.Socket;
public class TCPChatServer {
private ServerSocket serverSocket;
public void start(int port) throws IOException {
serverSocket = new ServerSocket(port);
Socket clientSocket = null;
try {
clientSocket = serverSocket.accept();
BufferedReader in = new BufferedReader(new InputStreamReader(clientSocket.getInputStream()));
PrintWriter out = new PrintWriter(clientSocket.getOutputStream(), true);
String inputLine;
while ((inputLine = in.readLine()) != null) {
System.out.println("Received message from client: " + inputLine);
out.println("Message received");
}
} finally {
if (clientSocket != null) {
clientSocket.close();
}
}
}
}
// TCP客户端类似
public class TCPChatClient {
private Socket socket;
// 发送接收消息、连接服务器等操作...
}
```
请注意,这只是一个基础示例,实际应用中需要处理异常、线程安全、错误检测等问题,并可能包含更复杂的交互机制。
阅读全文