2012-06-19 68 views
-2

嗨社區我有以下ServerSocket應該監聽端口53000並記錄任何收到的數據。但是,我似乎無法通過server.accept()阻止調用。ServerSocket Android

public void run() { 

     SocketServer server = new ServerSocket(53000); 


     //---buffer store for the stream--- 
     byte[] buffer = new byte[1024]; 
     //---bytes returned from read()--- 
     int bytes; 

     //---keep listening to the InputStream until an 
     // exception occurs--- 
     while (true) { 
      try { 

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

       String str = in.readLine(); 

       Log.i("received response from server", str); 

       in.close(); 
       socket.close(); 

      } catch (IOException e) { 
       Log.e(TAG, e.getMessage()); 
      } catch (Exception e){ 
       server.close(); 
       Log.e(TAG, e.getMessage()); 
      } 
     } 

    } 

我也給應用程序的清單文件INTERNET權限。 ()

爲了增加神祕感,我也驗證了客戶端的響應被髮送到那個端口。

有什麼特別的我需要做的,以使這項工作?

謝謝。

回答

4

你的代碼非常混亂,甚至不會編譯。我做了一些調整,以便我可以測試你的代碼,並且工作正常。下面是我使用的測試應用程序:

package com.test.stackoverflow 

import java.io.BufferedReader; 

public class ServerSocketTestActivity extends Activity { 
    /** Called when the activity is first created. */ 
    private static String TAG = "ServerSocketTest"; 

    private ServerSocket server; 

    Runnable conn = new Runnable() { 
     public void run() { 
      try { 
       server = new ServerSocket(53000); 

       while (true) { 
        Socket socket = server.accept(); 
        BufferedReader in = new BufferedReader(
          new InputStreamReader(socket.getInputStream())); 

        String str = in.readLine(); 

        Log.i("received response from server", str); 

        in.close(); 
        socket.close(); 
       } 
      } catch (IOException e) { 
       Log.e(TAG, e.getMessage()); 
      } catch (Exception e) {    
       Log.e(TAG, e.getMessage()); 
      } 
     } 
    }; 

    @Override 
    public void onCreate(Bundle savedInstanceState) { 
     super.onCreate(savedInstanceState); 
     setContentView(R.layout.main); 

     new Thread(conn).start(); 
    } 

    @Override 
    protected void onPause() {  
     super.onPause(); 
     if (server != null) { 
      try { 
       server.close(); 
      } catch (IOException e) { 
       e.printStackTrace(); 
      } 
     } 
    } 
} 

使用這個代碼,並通過netcat的運行adb shell我能夠連接,並與應用程序進行通信。

+0

謝謝羅德里戈。你是對的,它確實有效。我不得不在服務器端修復它。感謝您的意見,下次我會發布更乾淨的代碼。 – DoubleDunk

0

當與客戶合作聲明這些方法 要訪問流

// gets the input stream // ObjectInputStream input; 
// gets the output stream // ObjectOutputStream output; 
// ServerSocket server; 
// Socket connection; 

也許你有一個其他類訪問套接字;

server = new ServerSocket(5001, 100); 

//步驟1創建套接字連接 服務器=新的ServerSocket(5001,100); 而(條件爲真)
//步驟2等待連接

//步驟3獲取流

//步驟4:進程的連接

//步驟5:關閉連接