下面的程序为利用Socket实现客户端和服务端通信,请填空把程序补充完整。 //服务器端(ServerTest.java文件清单:) import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.io.PrintWriter; import java.net.ServerSocket; import java.net.Socket; class Server
时间: 2024-03-22 20:40:36 浏览: 64
Test{
public static void main(String[] args) throws IOException {
ServerSocket serverSocket = new ServerSocket(8888);
System.out.println("服务器已启动,等待客户端连接...");
Socket socket = serverSocket.accept();
System.out.println("客户端已连接,客户端信息如下:" + socket);
BufferedReader reader = new BufferedReader(new InputStreamReader(socket.getInputStream()));
PrintWriter writer = new PrintWriter(socket.getOutputStream(), true);
while (true) {
String message = reader.readLine();
if (message == null) {
break;
}
System.out.println("客户端发送的消息是:" + message);
writer.println("已收到消息:" + message);
}
reader.close();
writer.close();
socket.close();
serverSocket.close();
}
}
// 客户端(ClientTest.java文件清单:)
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.Socket;
import java.net.UnknownHostException;
class ClientTest {
public static void main(String[] args) throws UnknownHostException, IOException {
Socket socket = new Socket("localhost", 8888);
System.out.println("已连接服务器,服务器信息如下:" + socket);
BufferedReader reader = new BufferedReader(new InputStreamReader(socket.getInputStream()));
PrintWriter writer = new PrintWriter(socket.getOutputStream(), true);
BufferedReader console = new BufferedReader(new InputStreamReader(System.in));
while (true) {
String message = console.readLine();
writer.println(message);
String response = reader.readLine();
System.out.println("收到服务器的回复:" + response);
}
}
}
阅读全文