Andrei0427
Andrei0427

Reputation: 573

Preventing crashing when listening for a connection in Java

Is there any way of preventing my application from temporarily crashing as soon as I create a socket? This program unfreezes as soon as it receives a connection but it can be misleading to users.

I have tried putting the socket creation methods etc. in a thread and running it from there but that did not work.

Edit: Unless it would be feasible to give the socket a set amount of time and then disconnect once it expires?

Upvotes: 0

Views: 83

Answers (2)

Kristaps Baumanis
Kristaps Baumanis

Reputation: 605

Running it in a separate thread is the right way, since the Socket.accept() call is blocking (i.e. it blocks the thread you call it on, until it gets a connection).

There must be something wrong with your thread architecture. Post some code and maybe I can tell You what exactly.

EDIT: Giving the socket a short timeout will either not avoid the blocking, or timeout before someone connects, while getting a connection before the timeout will not have any difference from the current setup.

Upvotes: 1

Mathias Schwarz
Mathias Schwarz

Reputation: 7197

You program does not crash, it is simply waiting for a connection because the java.io library is blocking.

To prevent waiting for a connection, you can either use the non-blocking java.nio classes or start a new Thread and let this new thread be the one that is waiting for the connection.

Upvotes: 0

Related Questions