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 array or similar of connected client objects
  • implement send() function in client class
  • implement broadcast() function loops through client list , sends each of them message (using aforementioned send() function
  • make sure keep track of (and remove) dead/disconnected clients list, otherwise you'll run trouble trying send them.

on client:

  • make sure send "connection terminated" message when close/disconnect tell server you're leaving (makes easier server remove you)

Comments

Popular posts from this blog

linux - Does gcc have any options to add version info in ELF binary file? -

android - send complex objects as post php java -

charts - What graph/dashboard product is facebook using in Dashboard: PUE & WUE -