Impulsado por eventos de sockets de Java

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.

¿Lo es?

preguntado el 09 de marzo de 12 a las 16:03

3 Respuestas

In an event driven environment a Toma de datagrama will incur lower network overhead but will not give you the reliability. Here is a tutoriales about writing datagram socket clients and servers.

respondido 09 mar '12, 16:03

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.

respondido 09 mar '12, 16:03

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.

respondido 09 mar '12, 16:03

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 - fuera_sid3r

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 en.wikipedia.org/wiki/New_I/O - Nikolái Fetissov

No es la respuesta que estás buscando? Examinar otras preguntas etiquetadas or haz tu propia pregunta.