我对 Sockets 有点陌生,我正在尝试编写一个程序,我基本上可以将一些简单的请求从客户端程序发送到服务器程序。现在我只想在客户端中有 1 或 2 个用户可以选择的选项。例如,如果用户在客户端中选择“选项 1”,则服务器会发回一条消息“您选择选项 1”等等,但我无法弄清楚如何读取客户端发送的服务器上的输入。
客户代码:
Socket socket = null;
try
{
System.out.println("Connecting to Server");
socket = new Socket("192.168.0.104", 7003);
socket.setSoTimeout(10000);
System.out.println("Connected");
InputStreamReader input = new InputStreamReader(socket.getInputStream());
BufferedReader buffer = new BufferedReader(input);
PrintWriter print = new PrintWriter(socket.getOutputStream(), true);
String line = buffer.readLine();
//Not Sure which buffer to user here
System.out.println("Option 1");
System.out.println("Option 2");
System.out.println("Option 3");
}
System.out.println("Closing Client Connection");
buffer.close();
input.close();
print.close();
socket.close();
System.exit(0);
服务器代码:
ServerSocket serverSock = null;
Socket standSock = null;
try
{
serverSock = new ServerSocket(7003);
standSock = serverSock.accept();
InputStreamReader input = new InputStreamReader(standSock.getInputStream());
BufferedReader read = new BufferedReader(input);
PrintWriter print = new PrintWriter(standSock.getOutputStream(), true);
String dateTime = (Calendar.getInstance()).getTime().toString();
print.println("You're connected to the Server at: " + dateTime);
print.println("Type Q to disconnect");
String line = read.readLine();
//Not sure what to do here
System.out.println("Client: " + line);
print.println("Server" + line);
System.out.println("Closing Server Connection");
read.close();
input.close();
print.close();
standSock.close();
我是否需要在 Clinet 中使用两个不同的 BufferedReader,一个用于用户输入,一个用于套接字?真的对这部分感到困惑。
谢谢