2012-01-12 160 views
5

當我嘗試使用以下代碼運行由echo服務器和android客戶端組成的測試時,我總是收到異常消息「套接字已關閉」。這段代碼可以簡單地將msg發送到服務器,並從服務器接收msg,但是如果您想同時執行這兩個操作,它就不起作用了......我很好奇它爲什麼會導致這種問題,我應該如何修復它,如果我希望它能夠先發送消息到回顯服務器Android套接字異常「套接字已關閉」

然後從回顯服務器接收消息?

  // Server IP address 
      InetAddress serverIp; 

      // try to connect Server 
      try { 

       // set up server IP address 
       serverIp = InetAddress.getByName("192.168.17.1"); 

       // set up port 
       int serverPort=12345; 

       // initiate socket connection 
       Socket clientSocket=new Socket(serverIp,serverPort); 

       BufferedOutputStream out = new BufferedOutputStream(clientSocket.getOutputStream()); 
       out.write("Send From Android1111, stitch ".getBytes()); 
       out.flush(); 

       //wait to receive Server's msg 
       BufferedReader br =new BufferedReader(new InputStreamReader(clientSocket.getInputStream())); 

       total.toString();*/ 
      // Display received msg with Toast 
       Toast.makeText(getApplicationContext(), br.readLine(), Toast.LENGTH_SHORT).show(); 

      //close connection 
       clientSocket.close();    

//    out.close(); 
//    out = null; 
      } catch (IOException e) { 
       // display exception with Toast 
       Toast.makeText(getApplicationContext(),e.toString(), Toast.LENGTH_SHORT).show(); 
      } 

不幸的是,它仍然無法正常工作......我跟着你的指示,並修改代碼以:

  // set up Server IP address 
      serverIp = InetAddress.getByName("192.168.2.2"); 

      // set up Server port 
      int serverPort=12345; 

      // initiate socket connection 
      Socket clientSocket=new Socket(serverIp,serverPort); 

       // open input and output stream 
      OutputStream out = clientSocket.getOutputStream(); 
      InputStream in = clientSocket.getInputStream(); 

      //send msg 
      out.write("Send From Android1111, bitch ".getBytes()); 


       // receive msg from server 
      byte[] buffer = new byte[in.available()]; 
      in.read(buffer); 
      String rMsg = new String(buffer); 
      Toast.makeText(getApplicationContext(), rMsg, Toast.LENGTH_LONG).show(); 

      //close input and output stream 
      in.close(); 
      out.close(); 

      //關閉連線 
     clientSocket.close(); 
     } catch (IOException e) { 
      // 出錯後顯示錯誤訊息Toast 
      Toast.makeText(getApplicationContext(),e.toString(), Toast.LENGTH_SHORT).show(); 
     } 

針對助手的方便,這裏的寫代碼服務器部分蟒蛇:

# Practice Echo Server Program written in Python 
import socket 

# host = '' means it binds to any available interface 
host = '' 
port = 12345 

# socket() function returns a socket object whose methods implement the various socket system calls. 
s = socket.socket(socket.AF_INET,socket.SOCK_STREAM) 

# Bind the socket to address. 
s.bind((host,port)) 

# Listen for connections made to the socket. The backlog argument specifies 
# the maximum number of queued connections and should be at least 0; 
# the maximum value is system-dependent (usually 5), the minimum value is forced to 0. 
s.listen(5) 

# Accept a connection. The socket must be bound to an address and listening for 
# connections. The return value is a pair (conn, address) where conn is a new socket 
# object usable to send and receive data on the connection, and address is the address 
# bound to the socket on the other end of the connection. 
conn, addr = s.accept() 
print 'Connected by', addr 

# Receive data from the socket. The return value is a string representing the data received. 
# The maximum amount of data to be received at once is specified by bufsize. See the Unix 
# manual page recv(2) for the meaning of the optional argument flags; it defaults to zero. 
# Note For best match with hardware and network realities, the value of bufsize should be 
# a relatively small power of 2, for example, 4096. 

while 1: 
    data = conn.recv(1024) 
    if not data: break 
    print 'received data is : ', repr(data) 
    conn.send(data) 

conn.close() 
+3

INTERNET權限盡量不要在這裏發表您的帖子「進攻性」的語言。謝謝。我爲你修好了。 – prolink007 2012-01-12 17:13:52

回答

5

我假設你按照錯誤的順序做正確的事情。可能是服務器速度太快,當你試圖讀取響應時,它已經被接收並消失了。

繼教程Reading from and Writing to a Socket

  1. 打開套接字
  2. 打開的輸入流和輸出流到插座中的規則。
  3. 根據服務器的協議讀取和寫入流。
  4. 關閉流。
  5. 關閉插座。

您是否看到區別?首先打開輸入和輸出流,然後開始發送您的請求。

我相信,如果你堅持這個命令它將工作。

+0

nope ...它仍然不適合我...這麼奇怪...它只是吐司顯示空白字符串這一次...怪異... – shanwu 2012-01-13 10:08:57

+1

@ user1145976請不要張貼代碼作爲答案。只需更新你的問題。關於你正在使用的代碼_in.available()_僅在某些情況下起作用。所以不要使用它。只需使用我喜歡的BufferedReader和_readLine()_的示例代碼即可。 – Robert 2012-01-13 10:12:56

-1

你的應用程序需要在AndroidManifest.xml中

<uses-permission android:name="android.permission.INTERNET"/> 
+0

我做了,它不起作用。 – shanwu 2012-02-06 13:14:06

+0

這不會導致'套接字關閉'異常。 – EJP 2016-01-19 01:47:09