2014-03-06 184 views
0

我正在嘗試編寫一個簡單的客戶端/服務器Echo應用程序,我的客戶端似乎在發送輸入,但服務器似乎並未將其接收併發回。客戶端服務器應用程序不能正常工作

這裏的服務器:

import java.io.*; 
import java.net.*; 

public class Server 
{ 
    public static void main(String args[]) throws Exception 
    { 
     int port = 2000; 
     ServerSocket serverSocket; 
     Socket client; 

     BufferedReader is = null; 
     BufferedWriter os = null; 

     serverSocket = new ServerSocket(port); 
     System.err.println("Server established on port " + port); 

     client = serverSocket.accept(); 
     System.err.println("Client connected"); 

     is = new BufferedReader(
       new InputStreamReader(client.getInputStream())); 
     os = new BufferedWriter(
       new OutputStreamWriter(client.getOutputStream())); 
     System.err.println("Server established on port " + port); 

     String message = ""; 

     while((message = is.readLine()) != null) 
     { 
      System.err.println("Messaged received " + message); 
      os.write(message); 
     } 

     is.close(); 
     os.close(); 
     serverSocket.close(); 
    } 
} 

然後,客戶看起來是這樣的:

import java.io.*; 
import java.net.Socket; 

public class Client 
{ 
    public static void main(String args[]) throws Exception 
    { 
     String host = "localhost"; 
     int port = 2000; 
     Socket socket; 

     socket = new Socket(host, port); 

     BufferedReader is = new BufferedReader(
       new InputStreamReader(socket.getInputStream())); 
     BufferedWriter os = new BufferedWriter(
       new OutputStreamWriter(socket.getOutputStream())); 
     System.err.println("Connected to " + host + " on port " + port); 

     BufferedReader br = 
       new BufferedReader(new InputStreamReader(System.in)); 

     String input = ""; 

     while((input = br.readLine()) != null) 
     { 
      System.out.println("Sending " + input); 
      os.write(input); 
      System.out.println("Receiving " + is.read()); 
     } 

     is.close(); 
     os.close(); 
     socket.close(); 
    } 
} 

我缺少什麼,我相信我可以俯瞰簡單的東西。

+0

在你給他們寫信之後沖洗流可能嗎?你也應該考慮使用ARM,或者最後嘗試捕捉來管理這些資源。 –

回答

2

在客戶端嘗試用最後的換行字符寫入消息:

os.write(input+"\n"); 

(或調用也newLine()

,由於服務器讀取行由行。

相關問題