multithreading - thread overwritten when new socket connects (Server/Client) multithread java -


i have cluedo game uni, have server class , clients connecting. each client connecting want start own serverthread socket of client connecting. thread listens incoming messages , tells server class send them client(s). problem: each time new client connects overwriting serverthread there 1 serverthread , have 1 each client. send json messages between clients , right receive message in serverthread reads last connected socket. how can solve this? added accept method in server guess mistake there anywhere. help! mauritius

server

public void accept() throws ioexception{         while(true){             socket socket = serversocket.accept();             runnable r = new serverthreadhandler(socket);             thread t = new thread(r);             t.start();         }     } 

serverthreadhandler:

public class serverthreadhandler implements runnable {     static socket socket=null;     protected   user client;     //private static  int i;     private static bufferedreader in;     private static outputstreamwriter out;      public  void createuser(string nick, string group, string[] ext) throws ioexception{         client = new user(nick, group, ext, null, false, 0, false, socket, socket.getport());     }      /**      * constructor-method      * @param sockets      */     serverthreadhandler(socket sockets){         socket = sockets;     }     public void run(){         server.setthreadlist(socket);         in = createreader();         out = createwriter();         //and on...     } } 

the logic mentioned in code snippet create many threads no. of clients connecting.

however, possible reason might be, since socket variable in serverthreadhandler static, subsequent threads being created overwrite same socket variable causing issue in created thread using socket variable.

you should consider, using non static variable socket in serverthreadhandler since runnable class should hold state , should not using static socket.

from understood question, createuser method instance method of serverthreadhandler. hence must have created instance of serverthreadhandler invoke createuser class. hence can access socket variable if instance variable.


Comments

Popular posts from this blog

javascript - Karma not able to start PhantomJS on Windows - Error: spawn UNKNOWN -

c# - Display ASPX Popup control in RowDeleteing Event (ASPX Gridview) -

Nuget pack csproj using nuspec -