i creating simple multiplayer android game. devices share information each other using sockets/serversockets. program works fine first run after compilation, if close application , start again program not work. here snippet of server code:
public void listen() { try { /** * creates new server socket. passing in 0, device select * available port open. makes possible avoid having hardcode * port. */ if (serversocket == null) serversocket = new serversocket(0); // sets port generated server port setlocalport(serversocket.getlocalport()); // run until program stops while (!stop) { // make server socket listen input setsocket(serversocket.accept()); log.d(tag, "socket opened"); // creates buffered reader in order read input input = new bufferedreader(new inputstreamreader(socket.getinputstream())); // listen messages while(!thread.currentthread().isinterrupted()) { try { // reads line string line; line = input.readline(); // if line not null call onreceive if (line != null) { onreceive(line); log.d(tag, "received: " + line); } log.d(tag, "received something"); } catch (ioexception e) { log.d(tag, "error"); } break; } // close input input.close(); log.d(tag, "socket closed"); } } catch (ioexception e) { e.printstacktrace(); } }
when code works following logcat messages:
05-08 15:00:54.186 11947-11965/com.example.trommemand.playerapp d/net﹕ socket opened 05-08 15:00:54.186 11947-11965/com.example.trommemand.playerapp d/net﹕ received: ok 05-08 15:00:54.186 11947-11965/com.example.trommemand.playerapp d/net﹕ received 05-08 15:00:54.186 11947-11965/com.example.trommemand.playerapp d/net﹕ socket closed
however, when not work following:
05-08 15:00:54.186 11947-11965/com.example.trommemand.playerapp d/net﹕ socket opened 05-08 15:00:54.186 11947-11965/com.example.trommemand.playerapp d/net﹕ socket closed
i suspect problem fail close sockets. have tried close serversocket, gives me error due line: setsocket(serversocket.accept());
any suggestions?
always close resources in finally
block. try closing input.close
in finally
block... this:
{ try { input.close(); } catch (ioexception e) { e.printstacktrace(); } }
see if works..
Comments
Post a Comment