2011-01-31 87 views
0

我有一個簡單的服務器上運行我的電腦和一個簡單的客戶端上我的HTC運行Android 2.2的慾望。如何獲得簡單的Android客戶端和PC服務器得到工作

服務器和客戶端都使用相同的端口。我將服務器ip硬編碼到客戶端代碼中。當我嘗試連接到使用Android客戶端上的客戶端運行的服務器拋出該異常:

IOException ...: java.net.SocketException: The operation timed out. 

下面是客戶端和服務器代碼的部分:

客戶端代碼

InetAddress addr; 
    Socket socket = null; 

    byte [] ipAddress = new byte[] {(byte)82,(byte)168,(byte)175,(byte)141}; 

    try{ 

    addr = InetAddress.getByAddress(ipAddress); 

    socket = new Socket(addr, 1234); 
    System.out.println("socket = "+socket); 

    BufferedReader in = new BufferedReader(
      new InputStreamReader(
      socket.getInputStream())); 

    PrintWriter out = new PrintWriter(
      new BufferedWriter(
      new OutputStreamWriter(socket.getOutputStream())),true); 

     out.println("hello"); 
     socket.close(); 
    } catch (UnknownHostException e) { 
    System.out.println("UnknownHostException ...: "+e); 
    } catch (IOException e) { 
    System.out.println("IOException ...: "+e); 
    } 

服務器代碼

ServerSocket ss = new ServerSocket(PORT); 
    System.out.println("Started:"+ss); 

    try{ 
    //block until a connection occures 
    Socket socket = ss.accept(); 

    try{ 
    System.out.println("Conncetion accepted:"+socket); 
    InputStream IS = socket.getInputStream(); 
    InputStreamReader ISR = new InputStreamReader(IS); 
    BufferedReader in = new BufferedReader(ISR); 

    OutputStream OS = socket.getOutputStream(); 
    OutputStreamWriter OSR= new OutputStreamWriter(OS); 
    BufferedWriter BW = new BufferedWriter(OSR); 
    //output automatically flushed by PrintWriter 
    PrintWriter out = new PrintWriter(BW,true); 

    while(true){ 
    String str = in.readLine(); 
    System.out.println("Client: "+str); 
    out.println("hi"); 
    } 
    }finally{ 
    System.out.println("Closing..."); 
    socket.close(); 
    } 
    }finally{ 
    ss.close(); 
    } 

此代碼使用wifi,但不通過3G。

任何幫助,歡迎...並提前感謝您。

回答

3

您可能使用路由器/無線接入點連接到互聯網?

如果您的路由器使用NAT protocol,則互聯網上的任何設備都無法打開與PC的連接。 NAT只允許PC打開與互聯網的連接,反之亦然。

因此,當您的手機在無線上,它可以連接到PC,因爲它們都在同一個網絡上,並且不使用NAT。當你的手機在3G上,並因此在互聯網上,而不是你的手機和PC之間的NAT。

解決方案:

你的路由器上啓用端口轉發,比你的應用程序連接到路由器的IP,這將轉發此連接到您的電腦。

+0

Kengo,謝謝你的回覆。那麼這意味着如果有NAT,就沒有tcp連接?或者有沒有解決這個問題的方法? – mnish 2011-01-31 12:58:39

相關問題