Can I have a program with 2 sockets in Java? -
this simple chat program in java. know can work done 1 socket wondering why not use 2 sockets?
this executes not work intended. kindly see code , find error. please me new this. server code below.
server.java
import java.io.*; import java.net.*; public class server { public static void main(string[] args)throws ioexception { serversocket ss=new serversocket(10001); socket s=ss.accept(); socket s1=new socket("localhost",10005); datainputstream di=new datainputstream(s.getinputstream()); dataoutputstream dot=new dataoutputstream(s.getoutputstream()); bufferedreader br=new bufferedreader(new inputstreamreader(system.in)); string str1="",str=""; while(str1!="exit"){ str=(string)di.readutf(); system.out.println("message="+str); system.out.println("enter message:"); str1=br.readline(); dot.writeutf(str1); dot.flush(); } di.close(); dot.close(); s1.close(); s.close(); ss.close(); } }
client code below kindly tell problem. know can work done 1 socket trying why not use 2 sockets.
client.java
import java.io.*; import java.net.*; public class client { public static void main(string[] args) throws ioexception{ serversocket ss; ss = new serversocket(10005); socket s=ss.accept(); socket s1=new socket("localhost",10001); datainputstream di=new datainputstream(s.getinputstream()); dataoutputstream dot=new dataoutputstream(s1.getoutputstream()); bufferedreader br=new bufferedreader(new inputstreamreader(system.in)); string str="",str1=""; while(str1!="exit"){ system.out.println("enter message:"); str1=br.readline(); dot.writeutf(str1); dot.flush(); str=(string)di.readutf(); system.out.println("message="+str); } dot.close(); di.close(); s1.close(); ss.close(); } }
yes, can open (within reason) many sockets want single jvm.
the problem code you're using blocking api, meaning thread doesn't return call br.readline()
, cannot more work (including waiting data on other sockets).
you've got couple of options:
- create thread per socket (being careful of resource limitations).
- use nio api inherently non-blocking.
Comments
Post a Comment