File APIs for Java Developers
Manipulate DOC, XLS, PPT, PDF and many others from your application.
The moose likes Sockets and Internet Protocols and the fly likes Socket.accept stuck in loop Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Java » Sockets and Internet Protocols
Bookmark "Socket.accept stuck in loop" Watch "Socket.accept stuck in loop" New topic

Socket.accept stuck in loop

Rob Brew
Ranch Hand

Joined: Jun 23, 2011
Posts: 101
Hi all.

I'm at a loss as i've studied the official Oracle documentation on how to handle sockets and this problem still remains:

The Core class (of which the above method is call from) never exits therefore the next command in the main function cannot execute.

"There" never gets printed.

Should i set up initNetworking as a thread?

Thread.sleep() needed.
Paul Clapham

Joined: Oct 14, 2005
Posts: 19973

Well, yeah. The line "serverSocket.accept()" is indeed waiting until a client connects. And then once that happens, it's going to accept the client and wait for the next one.

So if you don't want that code to block something else, then yes, you should run it in its own thread.
Jeff Verdegan

Joined: Jan 03, 2004
Posts: 6109

Rob Brew wrote:
Should i set up initNetworking as a thread?

AS a thread? No. But IN its own thread, yes.

If you do

Obviously, you'll never get to the "other stuff" part. It doesn't matter if the "stuff" part is socket calls or something else.

Also, you're closing the ServerSocket at every pass through the while loop. This means that only your first accept() will work, and all subsequent ones will fail.

Always close in a finally block.

Campbell Ritchie

Joined: Oct 13, 2005
Posts: 46334
Question too difficult for “beginning”. Moving thread.
I agree. Here's the link:
subject: Socket.accept stuck in loop
It's not a secret anymore!