2011-12-16 141 views
0

我在使用套接字連接PC(簡單的Java服務器)和android模擬器時遇到了麻煩。連接建立後,服務器發送數據,但當我嘗試在android上讀取它時,它總是讀取一個空字符串。下面是我的一些代碼部分:本地PC服務器和android模擬器之間的套接字連接

服務器:

serverSocket = new ServerSocket(8888); 
socket = serverSocket.accept(); 
PrintWriter output = new PrintWriter(socket.getOutputStream(), true); 
output.write("Output string"); 
socket.close(); 

客戶:

socket = new Socket("10.0.2.2", 8888); 
input = new BufferedReader(new InputStreamReader(socket.getInputStream())); 
String s = input.readLine(); 
Log.i(TAG, s); 
socket.close(); 

我省略了嘗試,漁獲物和日誌清晰。根據日誌,連接建立,服務器發送數據,但客戶端只接收空字符串。我會很感激任何幫助。

+0

「連接被拒絕」錯誤發生。 – 2011-12-16 11:37:18

回答

2

這對我的作品...(此代碼僅用於寫入和服務器和客戶端讀取套接字數據)

服務器:

BufferedOutputStream bos = new BufferedOutputStream(connection. 
     getOutputStream()); 

    /** Instantiate an OutputStreamWriter object with the optional character 
    * encoding. 
    */ 
    OutputStreamWriter osw = new OutputStreamWriter(bos, "US-ASCII"); 

    String process = "Calling the Socket Server on "+ host + " port " + port; 

    /** Write across the socket connection and flush the buffer */ 
    osw.write(process); 
    osw.flush(); 

客戶:

/** Instantiate a BufferedInputStream object for reading 
     /** Instantiate a BufferedInputStream object for reading 
     * incoming socket streams. 
     */ 

     BufferedInputStream bis = new BufferedInputStream(connection. 
      getInputStream()); 
     /**Instantiate an InputStreamReader with the optional 
     * character encoding. 
     */ 

     InputStreamReader isr = new InputStreamReader(bis, "US-ASCII"); 

     /**Read the socket's InputStream and append to a StringBuffer */ 
     int c; 
     while ((c = isr.read()) != 13) 
     instr.append((char) c); 

     /** Close the socket connection. */ 
     connection.close(); 
     System.out.println(instr); 
    } 
    catch (IOException f) { 
     System.out.println("IOException: " + f); 
    } 
    catch (Exception g) { 
     System.out.println("Exception: " + g); 
    } 

希望這能幫到你..

+0

我發現了這個問題:我忘了使用output.flush(); – 2011-12-16 12:18:23

0

模擬器監聽他自己的「本地」網絡端口。 您應該從本地PC向仿真器端口呼叫端口。

閱讀android adb端口轉發。

+0

這並沒有幫助我。連接建立並且端口被客戶端接受 - 但仍然客戶端無法通過此套接字接收數據發送 - 服務器發送一些字符串,但客戶端只接收空字符串。 – 2011-12-16 11:52:08

2

喜@yuriy沒有什麼是你的代碼錯誤其實你不寫全行輸出流,以它給錯誤使用它,它爲我工作

serverSocket = new ServerSocket(8888); 
    socket = serverSocket.accept(); 
    PrintWriter output = new PrintWriter(socket.getOutputStream(), true); 
    output.println("Output string"); 
    socket.close(); 

只是output.println取代output.write在服務器

相關問題