简体   繁体   中英

Java Multithreaded server not working

So I'm trying to create a Server/Client in Java to improve my skills. But.. For some reason, though I create a new thread each time the server accepts a connection, things just don't work and only one client is working.
Here''s the code:

  while (true) {
            Socket client = null;
            client = server.accept();
            new Thread(new Server(client)).run();
        }

And I have no idea why it's happening. I use a tutorial for this and yet, things don't work. Thanks!

So, here's the solution for the problem.

"So what is difference between start and run method? Main difference is that when program calls start() method a new Thread is created and code inside run() method is executed in new Thread while if you call run() method directly no new Thread is created and code inside run() will execute on current Thread. Quoted from http://javarevisited.blogspot.com/2012/03/difference-between-start-and-run-method.html

Changing the .run() function to .start() solved the problem. Enjoy.

Kryonet is a very good Java library which provides a clean and simple API for efficient TCP and UDP client/server network communication using NIO.

It will make your network programming work a lot more easier, and you can get a better understanding of how to write client and server side code.

I would suggest that you try out your network programming skills using this library first and then try implementing your own.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM