我正在編寫一個使用套接字進行雙向通信的程序。客戶端程序向用戶提供一些選項,當用戶選擇該選項時,它將被服務器程序處理,並將結果返回給客戶端程序。我在服務器程序中遇到了一些麻煩,因爲如果我將它放入條件語句中,它將不會處理PrintWriter語句,如下圖所示。Java中的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);
在條件語句中,程序只是掛起並最終超時,但如果我移動該狀態nt在條件聲明外運行。如果我將它放入條件聲明中,爲什麼它不能工作?
它是PrintWriter延遲發送,而不是DataOutStream,它是無緩衝的。 – EJP
我同意DataOutStream是無緩衝的,並且PrintWriter默認延遲,但是當您在PrintWriter對象的構造函數中將autoflush設置爲true時,則不會。 –