Socket Android excepción "socket está cerrado"

Cuando intento ejecutar una prueba compuesta de un servidor de eco y un cliente android con el código siguiente, siempre obtengo la excepción msg "socket is closed". Este código simplemente puede enviar msg al servidor, y recibir msg desde el servidor, pero si quieres hacer los dos al mismo tiempo, simplemente no funciona … Estoy muy curioso por qué va a conducir a este tipo de problema, Y cómo debo solucionarlo si quiero que pueda enviar primero msg al servidor de eco

Y luego recibir msg desde el servidor de eco?

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

Desafortunadamente, sigue sin funcionar … Seguí tus instrucciones y modificó el código para:

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

Para la comodidad del ayudante, aquí está el código escrito python para la parte del servidor:

 # 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() 

Supongo que está haciendo las cosas correctas en el orden equivocado. Puede ser el servidor es demasiado rápido y cuando usted está tratando de leer la respuesta ya se ha recibido y se ha ido.

Siguiendo las reglas presentadas en el tutorial Leer y escribir en un socket

  1. Abrir un socket
  2. Abra un flujo de entrada y una salida de flujo al socket.
  3. Leer y escribir en el flujo de acuerdo con el protocolo del servidor.
  4. Cierre los arroyos.
  5. Cierre el zócalo.

¿Ves la diferencia? Primero abra el flujo de entrada y salida y luego comience a enviar su solicitud.

Estoy seguro de que si se adhieren a esta orden que funcionará.

Su aplicación necesita permiso de INTERNET en su AndroidManifest.xml

 <uses-permission android:name="android.permission.INTERNET"/> 
  • Android socket de programación ... ¿qué da?
  • Envío de datos TCP desde Android (como cliente) - ¿no se envían datos?
  • Conexión de socket SSL
  • Comunicación de LocalSocket con el dominio de Unix en Android NDK
  • Cómo desbloquear InputStream.read () en Android?
  • Llegar a un dispositivo de red por IP y puerto mediante el emulador de Android
  • Java socket IOException - permiso denegado
  • Captura de paquetes de red en Android?
  • Tiempo de espera de conexión de socket Android
  • Conexión de dos teléfonos Android para transferir datos entre ellos a través de WIFI
  • Android juego multi-jugador a través de la red
  • FlipAndroid es un fan de Google para Android, Todo sobre Android Phones, Android Wear, Android Dev y Aplicaciones para Android Aplicaciones.