Intriguing
Intriguing

Reputation: 135

How to set a time limit for ServerSocket to wait for the Client Socket to get connected

I am programming in java using Sockets and facing this below metioned issue.

I programmed a Server program which sends a plain text to the client side.When I start the server the server program waits for a long time for the client socket to get connected.But i want the server program to wait only for a specified time say 5 minutes and then report the user that the Client is not connected within the Specified time. I am unable to understand how to implement it.I have gone through Timer and TimerTask classes but its a bit confusing.

Upvotes: 3

Views: 5097

Answers (2)

Ankur Shanbhag
Ankur Shanbhag

Reputation: 7804

Use ServerSocket.setSoTimeout(int timeOut) to wait for the client. Set it to 0 if you need to wait infinitely.

Note: Java doc says:

The option must be enabled prior to entering the blocking operation to have effect.

Upvotes: 5

Yaozhen
Yaozhen

Reputation: 33

As java API doc describes 'Socket.accept()': Throws: IOException - if an I/O error occurs when waiting for a connection. SecurityException - if a security manager exists and its checkAccept method doesn't allow the operation. SocketTimeoutException - if a timeout was previously set with setSoTimeout and the timeout has been reached.

See Java API Doc Socket

Upvotes: 1

Related Questions