2011-05-09 31 views
0

我寫了一個與socket通信的程序,但我不知道他們爲什麼不工作。我的socket程序有問題

服務器代碼:

this.serverSocket = new ServerSocket(ServerConnector.port); 
     this.socketListener = this.serverSocket.accept(); 
     System.out.println(this.socketListener.getPort()); 

     this.objIn = new ObjectInputStream(this.socketListener.getInputStream()); 
     System.out.println("1"); 

     this.objOut = new ObjectOutputStream(this.socketListener.getOutputStream()); 
     System.out.println("1"); 

     this.objOut.writeInt(19999); 
     System.out.println("1"); 

     this.objOut.writeObject(new Date()); 
     System.out.println("1"); 

客戶端代碼:

this.clientSocket = new Socket(ClientConnector.host, ClientConnector.port); 

     System.out.println(this.clientSocket.getPort()); 
     this.objIn = new ObjectInputStream(this.clientSocket.getInputStream()); 
     System.out.println("1"); 
     this.objOut = new ObjectOutputStream(this.clientSocket.getOutputStream()); 
     System.out.println("1"); 

     int i = (Integer) this.objIn.readInt(); 
     System.out.println(i); 
     Date date = (Date) this.objIn.readObject(); 

事實是,他們不顯示我建議通過(19999和日期)的任何信息,甚至還可以」打印一行「1」(我添加了測試)。這意味着即使下面的線路也不能正常工作。我真的很困惑這些,誰可以找出錯誤?

this.objIn = new ObjectInputStream(this.clientSocket.getInputStream()); 

回答

-1

你最有可能遇到的Nagle's Algorithm效果。它試圖優化TCP中的數據包發送。如果您想立即發送數據,則需要在套接字接口上使用setTcpNoDelay方法將其禁用。

P.S.不知道爲什麼這個問題被標記爲osgi,因爲它根本與OSGi沒有關係。

+0

如果服務器端沒有打印出單行「1」,那麼套接字甚至沒有連接...您確定端口號對於客戶端和服務器是否相同? – smichak 2012-04-15 20:00:27

+0

我假設OP確實有成功的連接,但也需要驗證。雖然我認爲這應該很容易檢測OP的一方,因爲連接應該拋出一個異常。 – lothar 2012-04-15 20:07:47