在以下的代码中,服务端创建TCP套接字,等待客户端连接,获取客户端输入流和输出流,循环接收客户端消息并回复。客户端创建TCP套接字,连接服务器,获取客户端输入流和输出流,循环发送消息到服务器,并接收服务器的回复。
服务端:
import java.net.*;
import java.io.*;
public class TCPServer {
public static void main(String[] args) throws Exception {
// 创建TCP套接字
ServerSocket serverSocket = new ServerSocket(8888);
while (true) {
// 等待客户端连接
Socket clientSocket = serverSocket.accept();
// 获取客户端输入流
BufferedReader inFromClient = new BufferedReader(new InputStreamReader(clientSocket.getInputStream()));
// 获取客户端输出流
DataOutputStream outToClient = new DataOutputStream(clientSocket.getOutputStream());
// 循环接收客户端消息并回复
String message;
while ((message = inFromClient.readLine()) != null) {
System.out.println("收到客户端 " + clientSocket.getInetAddress() + ":" + clientSocket.getPort() + " 的消息: " + message);
// 回复消息给客户端
outToClient.writeBytes("已收到消息: " + message + "\n");
}
// 关闭客户端套接字
clientSocket.close();
}
}
}
客户端:
import java.net.*;
import java.io.*;
public class TCPClient {
public static void main(String[] args) throws Exception {
// 创建TCP套接字
Socket clientSocket = new Socket("localhost", 8888);
// 获取客户端输出流
DataOutputStream outToServer = new DataOutputStream(clientSocket.getOutputStream());
// 获取客户端输入流
BufferedReader inFromServer = new BufferedReader(new InputStreamReader(clientSocket.getInputStream()));
// 循环发送消息
String message;
while ((message = getUserInput()) != null) {
// 发送消息到服务器
outToServer.writeBytes(message + "\n");
// 接收服务器回复
String modifiedMessage = inFromServer.readLine();
System.out.println("收到服务器的回复: " + modifiedMessage);
}
// 关闭客户端套接字
clientSocket.close();
}
}