我正在编写一个使用套接字进行 2 路通信的程序。客户端程序向用户提供一些选项,当用户选择该选项时,服务器程序会对其进行处理并将结果返回给客户端程序。我在使用服务器程序时遇到了一些问题,因为如果我将 PrintWriter 语句放在我的条件语句中,它不会处理它,如下所示。
客户:
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");
DataOutputStream os = new DataOutputStream(socket.getOutputStream());
InputStreamReader userInput = new InputStreamReader(System.in);
BufferedReader userBuffer = new BufferedReader(userInput);
InputStreamReader serverInput = new InputStreamReader(socket.getInputStream());
BufferedReader serverBuffer = new BufferedReader(serverInput);
PrintWriter print = new PrintWriter(socket.getOutputStream(), true);
System.out.println("Option 1");
System.out.println("Option 2");
System.out.println("Option 3");
String userOption = userBuffer.readLine();
os.writeBytes(userOption);
if (userOption.equals("1"))
{
String line = serverBuffer.readLine();
System.out.println(line);
}
System.out.println("Closing Client Connection");
serverBuffer.close();
serverInput.close();
print.close();
socket.close();
os.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(), false);
String dateTime = (Calendar.getInstance()).getTime().toString();
if (read.readLine().equals("1"))
{
System.out.println("Option 1");
print.println("You're connected to the Server at: " + dateTime);
}
System.out.println("Closing Server Connection");
read.close();
input.close();
print.close();
standSock.close();
}
我已经测试了来自客户端程序的用户输入并正确获取它,但问题是如果我移动
print.println("You're connected to the Server at: " + dateTime);
在条件语句中,程序只是挂起并最终超时,但是如果我将该语句移到条件语句之外,它就可以工作。如果我把它放在我的条件语句中,为什么它不能工作?