java - Threads & networking issue -
given following code:
client c1 = new client(); c1.connect("127.0.0.1",1300); connect function:
public void connect(string servername, int port) { try { socket socket = new socket(servername,port); connection = new connectionproxy(socket); connection.start(); } catch(ioexception e) { e.printstacktrace(); } } (connectionproxy class extends thread) :
public class connectionproxy extends thread { private socket socket; private inputstream is; private outputstream os; private stringconsumer client; public connectionproxy(socket socket) { this.socket = socket; try { = socket.getinputstream(); os = socket.getoutputstream(); } catch(ioexception e) { e.printstacktrace(); } } public void run () { datainputstream dis = new datainputstream(is); dataoutputstream dos = new dataoutputstream(os); while (socket != null) { try { string msg = dis.readutf(); system.out.println(msg); } catch(ioexception e) { e.printstacktrace(); } } } i'm trying implement chat , i'm finding difficult send message written client of connected clients.
how that? should hold reference each object (like c1) on server side, or should hold connectionproxy thread on server side? if not, how implement correctly , efficiently?
would love help! thanks!
without being given code, i'll outline you'd want achieve goal.
on server:
- keep
arrayor similar of connectedclientobjects - implement
send()function inclientclass - implement
broadcast()function loops through client list , sends each of them message (using aforementionedsend()function - make sure keep track of (and remove) dead/disconnected
clientslist, otherwise you'll run trouble trying send them.
on client:
- make sure send "connection terminated" message when close/disconnect tell
serveryou're leaving (makes easier server remove you)
Comments
Post a Comment