this question has answer here:
- example socket app doesn't work 1 answer
i'm new java.net , trying make simple client-server app. here server code:
public class consumer extends thread{ public socket s; int num; public consumer(int num, socket s){ this.num = num; this.s = s; setdaemon(true); setpriority(norm_priority); start(); } public static void main(string args[]){ try { int = 0; serversocket server = new serversocket(3128, 0, inetaddress.getbyname("localhost")); system.out.println("server started"); while (true){ new consumer(i, server.accept()); i++; } } catch (exception e){ } } public void run(){ try { inputstream = s.getinputstream(); outputstream os = s.getoutputstream(); byte buf[] = new byte[64*1024]; int r = is.read(buf); string data = new string(buf, 0, r); data = "" +num+": " +"\n" + data; os.write(data.getbytes()); s.close(); } catch (exception e){ system.out.println("init error: " + e); } } }
when start - nothing bad happens when send smth client following:
init error: java.lang.stringindexoutofboundsexception: string index out of range: -1
how fix it?
when read data input stream, know you've reached end of stream when read
returns -1. looks that's happens here: r comes out -1 because there's no data read, , program goes on try create string negative number of characters.
you should check return values of functions error conditions:
int r = is.read(buf); if (r < 0) return; /* end of stream reached */
also, when handling exceptions should print stack trace. stack trace tells on line of program exception happened. without information have start debugging process guessing.
} catch (exception e){ system.out.println("init error: " + e); e.printstacktrace(); }
Comments
Post a Comment