Advertisement

[java] ServerSocket.accept()

Started by November 12, 2000 05:27 AM
3 comments, last by moregames 24 years, 2 months ago
Why don''t most coders place ServerSocket.accept() in a thread? In most examples and code I''ve seen they place it in a regular method or in main. I guess there are no drawbacks to this?
I was thinking probably accept() starts its own method and doesnt slow down the system. So if i place accept in another thread, I''ll just be wasting resources/cpu?
Advertisement
Well, personally I start a new thread for the accept, but I guess if you aren''t going to do anything more with the main-thread (it usually just runs out, leaving the AWT-thread to keep your app running), you might as well tie it up to an Accept.
Cuss ServerSocket.accept() _waits_ for and returns a socket connection. This is bad if you want do do something whilst waiting for a client to connect....
It all really depends on how you go about what your doing, and exactly what it is your doing...

say for example.. your doing a simple java web server...

You could have a loop that simply is:

..
while(true)
{
Socket socket = ServerSocket.accept();
new Thread(new Connection(socket)).start();
}
..

and the Connection object reads in the HTTP request, and passes back the neccessary data, and then it is destroyed.

In a case like this, you WANT the program to wait for the connection, however the connection objects run on their own threads, oblivious to the waiting state of the ServerSocket...

However.. if you want a game to play.. and have players come and go.. well.. then you would want your ServerSocket.accept() on a completley different thread, as you want other things to occur while having the port open.

It really all depends.

Mark



----
www.emanatemultimedia.com
----
<< ...and here is one we developed earlier... >>

This topic is closed to new replies.

Advertisement