java - Listening on multiple sockets (InputStreamReader) -
i'm having problem little game i'm designing in class. problem got 2 clients connected server. (client1 , client2) each running game, in end, closes window. game window jdialog, then, when it's closed, send message, through socket, server, telling it's done. want server know of 2 clients completed first. reporting through printwriter on sockets' outputstream. did this:
in1 = new bufferedreader(new inputstreamreader(client.getinputstream())); in2 = new bufferedreader(new inputstreamreader(client2.getinputstream())); try { in1.readline(); } catch (ioexception ex) { logger.getlogger(gameserver.class.getname()).log(level.severe, null, ex); } try { in2.readline(); } catch (ioexception ex) { logger.getlogger(gameserver.class.getname()).log(level.severe, null, ex); }
problem waits first input, before starts listening on second. how can make listen on both @ same time? or solve problem other way. thanks!
server connection should work this:
server gameserver = new server(); serversocket server; try { server = new serversocket(10100); // .. server setting should done here } catch (ioexception e) { system.out.println("could not start server!"); return ; } while (true) { socket client = null; try { client = server.accept(); gameserver.handleconnection(client); } catch (ioexception e) { e.printstacktrace(); } }
in hanleconnection() start new thread , run communication client in created thread. server can accept new connection (in old thread).
public class server { private executorservice executor = executors.newcachedthreadpool(); public void handleconnection(socket client) throws ioexception { playerconnection newplayer = new playerconnection(this, client); this.executor.execute(newplayer); } // add methods handle requests playerconnection }
the playerconnection class:
public class playerconnection implements runnable { private server parent; private socket socket; private dataoutputstream out; private datainputstream in; protected playerconnection(server parent, socket socket) throws ioexception { try { socket.setsotimeout(0); socket.setkeepalive(true); } catch (socketexception e) {} this.parent = parent; this.socket = socket; this.out = new dataoutputstream(socket.getoutputstream());; this.in = new datainputstream(socket.getinputstream()); } @override public void run() { while(!this.socket.isclosed()) { try { int nextevent = this.in.readint(); switch (nextevent) { // handle event , inform server } } catch (ioexception e) {} } try { this.closeconnection(); } catch (ioexception e) {} } }
Comments
Post a Comment