2013-04-04 111 views
0

感謝大家看到我的問題。 我想用java解釋我在Socket上的問題。 使用套接字,一個用於服務器等待來自客戶端的連接,另一個用於客戶端與服務器連接。 有兩個問題~~使用java編碼運行服務器和客戶端應用程序

(1)

+++之後它們都彼此連接,所述兩個側可以交換消息給對方。我已經用服務器和客戶端完成了兩個應用程序代碼,每個代碼都有自己的主要代碼THREAD,但我不能讓它們彼此通信。我使用Windows命令來運行這兩個文件.class。我先運行服務器,然後運行客戶端。他們不能相互溝通。我想知道這是否是一個堵塞問題。如果我建立另一個線程,這個問題可以解決? (2)我試圖在兩個eclipse上運行這兩個應用程序,換句話說每個eclipse運行一個應用程序。爲什麼這個問題可以解決?

(3)這裏是我的代碼客戶端:

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

public class CC { 
    public static void main(String args[]){ 
     Socket client=null; 
     DataInputStream in=null; 
     DataOutputStream out=null; 
     try{ 
       client=new Socket("127.0.0.1",2060); 
       in=new DataInputStream(client.getInputStream()); 
       out=new DataOutputStream(client.getOutputStream()); 
       System.out.println("You are a client,you send message to server"); 
       Scanner cin=new Scanner(System.in); 
       while(true){ 
       String send=null,receive=null; 
       System.out.println("Please input Client message sending to server!"); 
       send=cin.nextLine(); 
       out.writeUTF(send); 
       receive=in.readUTF(); 
       System.out.println("Message from Server is:"+receive); 
       Thread.sleep(500); 
       } 
     } 

     catch(Exception e){ 
      System.out.println("break!"+e); 

     } 

    }  

}

這裏是我的服務器

import java.util.*; 
import java.io.*; 
import java.net.*; 
public class SS { 
    public static void main(String args[]){ 
     ServerSocket socketServer=null; 
     DataInputStream in=null; 
     DataOutputStream out=null; 
     Socket server; 
     try{ 
      socketServer=new ServerSocket(2060); 
     } 
     catch(Exception e1){ 
      System.out.println("can't estblish socketServer "+e1); 
     } 
     try{ 
      Scanner cin=new Scanner(System.in); 
      System.out.println("you are server ,please send message to client"); 
      server=socketServer.accept(); 
      in=new DataInputStream(server.getInputStream()); 
      out=new DataOutputStream(server.getOutputStream()); 
      while(true){ 
       String send=null,receive=null; 
       receive=in.readUTF(); 
       System.out.println("get message from client is "+receive); 
       System.out.println("send message from client"); 
       send=cin.nextLine(); 
       out.writeUTF(send); 
     } 
     } 
     catch(Exception e){ 
     System.out.println("break! "+e); 
     } 
    }  
} 
+0

「他們都互相聯繫後,雙方可以互相交換信息」,「但我不能讓他們相互溝通」是衝突的。你在每個這些程序的控制檯上看到什麼?另外,除非要將輸入從服務器發送到客戶端,否則在服務器代碼中不需要「掃描程序」。 – asgs 2013-04-04 17:43:55

回答

0

服務器端和客戶端代碼的死鎖代碼。

在您編寫的客戶端代碼send=cin.nextLine();中阻塞,直到有更多的輸入可用。在您編寫的服務器代碼中,receive=in.readUTF();也會阻塞,直到輸入可用。

也就是說,建立連接後,服務器和客戶端都希望對方發送導致死鎖的事件,並且兩者都會無限期地等待。

您必須確保服務器或客戶端在等待接受輸入之前先發送一些輸出。

+0

謝謝,我已經解決了我的朋友們下面的這個問題。因爲我之前運行過這個應用程序,所以端口已經被佔用了。然後我第二次運行這個應用程序,這個結果這兩個應用程序不能傳輸消息。這兩個應用程序是完全正確的。 – 2013-04-08 15:37:21

0

謝謝,我已經解決了我的朋友們下面的這個問題。因爲我之前運行過這個應用程序,端口已經被佔用了。於是我第二次運行這個應用程序,這個結果這兩個應用程序不能傳輸消息。這兩個應用程序是完全正確的。

相關問題