Re: event driven socket
"asit" <lipun4u@gmail.com> wrote in message
news:65843a41-5270-4c13-81ae-9a9ff2effa27@d36g2000prb.googlegroups.com...
How can this be done ???
I usually start by looking at the JavaDocs for sockets, threads, etc., to
understand the APIs, and by reading the relevant tutorials. For over ten
years, java.sun.com has been my one-stop-shop for the majority of my Java
knowledge. Read section 6 - Events from the Java Beans spec
(http://java.sun.com/javase/technologies/desktop/javabeans/docs/spec.html)
for sample code showing how to write event sources and how to define event
listener interfaces.
Give some more specific information ???
What would you like to know, specifically?
Create a class to hold the socket and a worker thread. The class needs to
provide a way to configure the socket (e.g., address:port, etc.) -- either
constructor parameters or properties -- your choice, and it also needs a
start or connect method, and probably a disconnect or close method.
The worker thread opens the socket, and then spins in a loop, reading the
input stream. Read blocks, waiting for data. When data is received, read
returns with data. The thread then fires an event with the received data and
whatever other information you want to include, and goes back to read again.
Your thread needs an exception handler for the various socket I/O
exceptions. The exception handler can also fire events to notify the
listener of error conditions. Closing the socket from either end usually
causes a blocked read to exit with an IOException, which your thread can use
to fire a socket closed event.
If you want to write to the socket, then you also need to define methods on
your outer class to write data to the socket output stream.
You have to do slightly different things if you have a server socket vs. a
client socket. A server socket needs a worker thread that accepts
connections, and then each connection might require its own thread to
monitor that connection. I will leave server sockets as an exercise for the
reader.