1

I am having java server and just one client at the time.

  • client connects and sends card ID (blocking read on server side is suitable, because only 1 client at the time)
  • if card doesn't exist in database it just sends back 0 and close the socket (no problem)
  • if card does exist sends back 1
  • now client has to send PIN to the server, but there has to be some timeout, let's say 10s. Here i cannot use blocking read, what should i do? Socket setSoTimeout is not an option, because first read is blocking but second one should not be.
Kara
  • 6,115
  • 16
  • 50
  • 57
ZmAY
  • 11
  • 2
  • Maybe you shuold consider threading. – px5x2 Apr 30 '14 at 12:59
  • Can you share some code so we can see how your doing things? If you just want your program to wait ten seconds before doing something particular you could use: – ObedMarsh Apr 30 '14 at 13:05

3 Answers3

0

My advice is to create a ExecutorService and start a thread with it.

There is a example here : http://docs.oracle.com/javase/7/docs/api/java/util/concurrent/ExecutorService.html

bitli
  • 575
  • 2
  • 14
0

The correct (but not the easiest) way to to this is to use java.nio.channels.SocketChannel. It's read method reads into a ByteBuffer. You combine it with a java.nio.channels.Selector to read from multiple sockets without blocking (the selector helps you find out which one has data available) but in your case you may simply be happy with the SocketChannel.

It is a lot harder to use though - there is no InputStream and you need to manage the ByteBuffer.

Another alternative is to start a watchdog Thread that sleeps for the duration of your timeout and then closes the Socket if the client hasn't sent the PIN yet. Closing the socket will interrupt a blocked reader.

Some older questions to help you with the SocketChannel if you want to go that way:

Erwin Bolwidt
  • 30,799
  • 15
  • 56
  • 79
  • Correct me if I am wrong but literally I think using SocketChannel is still in blocking mode. It is just that you can check to read from multiple sockets instead of waiting at only 1 socket. – HieuHT Feb 06 '19 at 14:04
  • Its stil in blocking mode but the selector will tell you when you can read without blocking. The socket only blocks when there are zero bytes available to be read. – Erwin Bolwidt Feb 06 '19 at 20:30
0

The server should always use a read timeout. You can vary it after the first request and response.

user207421
  • 305,947
  • 44
  • 307
  • 483