java - Sockets readInt not always working -
i'm building client-server java application. problem that, when send integer writeint(), blocks on readint().
client
printwriter socketout = new printwriter(sock.getoutputstream()); dataoutputstream d = new dataoutputstream(sock.getoutputstream()); string s = "user"; socketout.println(s); socketout.flush(); d.writeint(data[0]); d.flush(); d.writeint(data[1]); d.flush();
server
while(true){ system.out.println("listening clients..."); clientsock = serversock.accept(); scanner in = new scanner(clientsock.getinputstream()); string clienttype = in.nextline(); switch(clienttype){ case "resource": new thread(new resourceservice(clientsock)).start(); break; case "user": new thread(new userservice(clientsock)).start(); break; } }
user thread
@override public void run(){ try{ datainputstream input = new datainputstream(user.getinputstream()); int = 0; int = input.readint(); // blocks here. int b = input.readint(); system.out.println(a); system.out.println(b); ...
i'm trying distinguish between clients based on first string sent server. server reads int, , blocks. example of output is:
listening clients... listening clients... listening clients... listening clients... listening clients... 1 // here server didn't block 100000 listening clients...
probably not idea use datainputstream/dataoutputstream mixed scanner , printwriter. scanner , printwriter recommended more user interaction.
try use dataoutputstream , datainputstream.
client
dataoutputstream d = new dataoutputstream(sock.getoutputstream()); string s = "user"; d.writeutf(s); d.writeint(data[0]); d.flush(); d.writeint(data[1]); d.flush();
server
datainputstream input = new datainputstream(clientsock.getinputstream()); string clienttype = input.readutf(); switch(clienttype){ case "resource": new thread(new resourceservice(input)).start(); break; case "user": new thread(new userservice(input)).start(); break;
user thread
int = input.readint(); int b = input.readint(); system.out.println(a); system.out.println(b);
note 1: datainputstream/dataoutputstream use own protocol write/read utf strings, no need use line termination.
note 2: methods of printwriter not throw i/o exceptions, have check calling checkerror
(probably not problem here).
Comments
Post a Comment