2012-01-12 34 views
5

Khi tôi cố chạy thử nghiệm bao gồm máy chủ echo và máy khách Android có mã sau, tôi luôn nhận được thông báo ngoại lệ "socket is closed". Mã này có thể đơn giản gửi thông điệp đến máy chủ, và nhận tin nhắn từ máy chủ, nhưng nếu bạn muốn làm cả hai cùng một lúc, nó chỉ không hoạt động ... Tôi rất tò mò tại sao nó sẽ dẫn đến loại vấn đề này, và làm cách nào để khắc phục sự cố nếu tôi muốn nó có thể gửi tin nhắn đầu tiên đến máy chủ echoỔ cắm Android ngoại lệ "được đóng"

và sau đó nhận tin nhắn từ máy chủ echo?

  // 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(); 
      } 

không may, nó vẫn không hoạt động ... Tôi đi theo hướng dẫn của bạn và thay đổi mã để:

  // 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(); 
     } 

để thuận tiện helper của, đây là trăn mã được viết cho phần máy chủ :

# 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

Cố gắng không để gửi tiếng "tấn công" trong bài viết của bạn ở đây. Cảm ơn bạn. Tôi cố định nó cho bạn. – prolink007

Trả lời

5

Tôi cho rằng bạn đang làm đúng thứ tự sai. Có thể máy chủ quá nhanh và khi bạn đang cố đọc phản hồi, nó đã được nhận và biến mất.

Tiếp theo các quy tắc thể hiện trong hướng dẫn Reading from and Writing to a Socket

  1. mở một ổ cắm
  2. mở thêm một input stream và output stream vào socket.
  3. Đọc và ghi vào luồng theo giao thức của máy chủ.
  4. Đóng các luồng.
  5. Đóng ổ cắm.

Bạn có thấy sự khác biệt không? Đầu tiên mở đầu vào và đầu ra dòng và sau đó bắt đầu gửi yêu cầu của bạn.

Tôi chắc chắn rằng nếu bạn tuân theo thứ tự này, nó sẽ hoạt động.

+0

nope ... nó vẫn không hoạt động đối với tôi ... thật kỳ lạ ... nó chỉ là bánh mì nướng hiển thị chuỗi trống lần này ... lạ ... – shanwu

+1

@ user1145976 Vui lòng không đăng mã làm câu trả lời. Chỉ cần cập nhật câu hỏi của bạn. về mã bạn đang sử dụng _in.available() _ chỉ hoạt động trong một số trường hợp nhất định. Do đó không sử dụng nó. Chỉ cần sử dụng mã mẫu tôi đã thích với một BufferedReader và _readLine() _. – Robert

-1

ứng dụng của bạn cần sự cho phép INTERNET trong AndroidManifest.xml của bạn

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

Tôi đã làm, nó không hoạt động. – shanwu

+0

Điều đó không gây ra ngoại lệ 'socket closed'. – EJP

Các vấn đề liên quan