sockets - Java Echo Server Not Working -
server code:
import java.net.*; import java.io.*; import java.util.*; class ecserver{ public static void main(string args[])throws exception{ serversocket ss=new serversocket(4019); socket so=ss.accept(); printstream pw=new printstream(so.getoutputstream()); string str; bufferedreader br=new bufferedreader(new inputstreamreader(so.getinputstream())); while(true) { str=br.readline(); system.out.println("client input : "+str); pw.println(str); if(str.equals(".")) break; } } }
client code:
import java.net.*; import java.io.*; class ecclient{ public static void main(string args[])throws exception{ socket so=new socket("localhost",4019); printstream ps=new printstream(so.getoutputstream()); bufferedreader br=new bufferedreader(new inputstreamreader(system.in)); bufferedreader br1=new bufferedreader(new inputstreamreader(so.getinputstream())); string str; str=br.readline(); while(!str.equals(".")) { ps.println(str); str=br1.readline(); system.out.println(str); str=br.readline(); } } }
the above code has 2 parts : client , server . m quite new java socket programming .
the server has server socket , socket type . message sent server client via 4019 port . server prints same message output , copy sent client server.
the clients job take line , send server return copy of message , print output.
the program terminates when "." encountered.
the problem when type message , send , both client , serve hang.
you not flushing output stream , reason server , clients hanging. either use ps.flush();
after writing socket or use auto flushing by:
printstream pw=new printstream(so.getoutputstream(), true);
and
printstream ps=new printstream(so.getoutputstream(), true);
on both ends. hope helps
Comments
Post a Comment