1

I have a client that will connect to a server through a socket. After connecting every event that happens on the server will be sent to all registered clients.

Every client should receive data related to the event.

I just need to implement the client...meaning I need to connect to the server and receive the events' data.

I was thinking on doing something like:

this.socket = new Socket(InetAddress.getByName(host),
this.socket.connect(socket.getLocalSocketAddress(), SOCKET_TIMEOUT);

And then launch a thread which gets the InputStream of the socket in a while loop.

But I don't know if this the best way to implement an event driven client through a socket.

Is it?

earcam
  • 6,662
  • 4
  • 37
  • 57
out_sid3r
  • 1,018
  • 2
  • 20
  • 42

3 Answers3

2

In an event driven environment a Datagram Socket will incur lower network overhead but will not give you the reliability. Here is a tutorial about writing datagram socket clients and servers.

Usman Ismail
  • 17,999
  • 14
  • 83
  • 165
0

This is often done by spawning a separate thread for the client that continuously makes blocking calls to read() from the stream - that way, as soon as data becomes available the read() call unblocks and can act on what it received ('the event fires'), then it goes back to blocking waiting for the next event.

JTeagle
  • 2,196
  • 14
  • 15
0

You don't necessarily need a thread here unless the client has to respond to some other input like GUI events.

Then, assuming you are talking about TCP, read from the socket in a loop, buffering received data until you have a complete application "event", and call your application "event handler". It's that simple.

Nikolai Fetissov
  • 82,306
  • 11
  • 110
  • 171
  • If I don't spawn a thread my application will block, right? I need to be constantly reading the socket which is a blocking operation, or am I wrong? Thx for the reply – out_sid3r Mar 09 '12 at 16:38
  • 2
    Yes, it will block reading the socket. Isn't that what you want? There's also non-blocking IO framefork in Java, check it out http://en.wikipedia.org/wiki/New_I/O – Nikolai Fetissov Mar 10 '12 at 07:43