2012-01-12 22 views
5

Quando provo a eseguire un test composto da un server echo e un client Android con il seguente codice, ottengo sempre il messaggio di eccezione "socket is closed". Questo codice può semplicemente inviare msg al server e ricevere msg dal server, ma se vuoi fare entrambe le cose nello stesso momento, non funziona ... Sono molto curioso del perché porterà a questo tipo di problema, e come dovrei risolverlo se voglio che sia in grado di inviare prima msg su echo serverEccezione socket Android "socket chiuso"

e quindi ricevere msg dal server 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(); 
      } 

purtroppo, ancora non funziona ... ho seguito la vostra istruzione e modificare il codice per:

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

per comodità di aiuto, ecco il pitone codice scritto da parte del server :

# 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

Cercate di non inviare linguaggio "offensivo" nei tuoi messaggi qui. Grazie. L'ho risolto per te. – prolink007

risposta

5

Suppongo che tu stia facendo le cose giuste nell'ordine sbagliato. Potrebbe essere il server è troppo veloce e quando si sta tentando di leggere la risposta è già ricevuto e andato.

Seguendo le regole presentate nel tutorial Reading from and Writing to a Socket

  1. Aprire una presa
  2. Aprire un flusso di input e output stream alla presa.
  3. Leggere e scrivere sullo stream in base al protocollo del server.
  4. Chiudere i flussi.
  5. Chiudere la presa.

Vedete la differenza? Per prima cosa apri il flusso di input e output e poi inizia a inviare la tua richiesta.

Sono sicuro che se continuerai a seguire questo ordine funzionerà.

+0

no ... non funziona ancora per me ... così strano ... è solo il brindisi mostrare questa stringa vuota questa volta ... strano ... – shanwu

+1

@ user1145976 Si prega di non postare il codice come risposta. Aggiorna la tua domanda. riguardo al codice che stai usando _in.available() _ che funziona solo in determinate circostanze. Quindi non usarlo. Basta usare il codice di esempio che mi è piaciuto con un BufferedReader e _readLine() _. – Robert

-1

L'applicazione ha bisogno di autorizzazioni Internet nella vostra AndroidManifest.xml

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

L'ho fatto, non funziona. – shanwu

+0

Ciò non ha causato eccezioni 'socket chiuso'. – EJP