Listener for incoming messages - java

I am currently trying to create a chat application using the Socket and ServerSocket classes, but i kinda ran into a roadblock. I need some kind of listener to execute a certain block of code when a message is incoming from the server or the client, but i can't seem to find one. An option would of course be to just check for incoming messages every 10 ms or something, but isn't there a smarter solution?

In general, you should assign a Thread to each Socket you are reading, so that Thread can block on the socket and wait for incoming information.
You should take a look at DataFetcher: http://tus.svn.sourceforge.net/viewvc/tus/tjacobs/io/
This class can work asynchronously, and notify a FetcherListener when new data is available

I recommend Netty or Mina. As for Socket and ServerSocket, the read() calls are blocked, so in a way the code below the read()s are executed whenever there's incoming data.
Beware of the incomplete message though, because Sockets provide a stream of bytes and the applications are usually more comfortable with discrete messages.

Related

How to wait on different events simultaneously

I have an open socket connection to a server.
On the one hand, in my code, I want to wait on a BlockingQueue for a message to be handed to me for sending to that server, then write it to the OutputStream.
When I send such a message, this normally expects an answer from the server (which needs to be read from the InputStream).
At the same time, I want to continuously listen on the socket's InputStream for spontaneous incoming messages from the server (server generated events).
Is there a recommended pattern for handling such a situation?
I obviously expect to have at least 2 threads involved (waiting on the two inputs - BlockingQueue and Socket). Any pointers are welcome on how to sync those, links to docs/blogs welcome.

How would i pause Scanner from reading to broadcast a message?

I am trying to implement a client-server application. Suppose i have two files, Server.java and Client.java. I am connected with both via DataOutputStream and DatainputStream and through socket programming. The clients have multi-threading implemented in Server.java.
Now the Server.java is doing a write.utf() to write a question to the Client.java, and the Client.java, in its terminal, is implementing a readUTF() and uses the Scanner class to get input from user keyboard.
Suppose now there is another client thread that wants to broadcast a message to all other clients. How would i stop/pause/lock the Scanner in the Client console to do a writeUTF() to the Client console to broadcast the message? The client should be able to resume its activity after the message is broadcasted.
One possible solution is to use a Queue. As you read in from the Scanner, messages can be placed in the Queue until they are sent out. When a broadcast needs to be made, it can be placed on the Queue (or perhaps on multiple queues depending on the situation). Just be sure that if you have multiple threads accessing a Queue, you are putting it in a synchronized block of code.
In a client-server situation, a LinkedBlockingQueue may be of use, as this will allow you to read from the Queue forever, and when it is empty, the client or server will simply wait for the Queue to get another item without any constant checking on your part.

Java: Multiple sockets send and receive maintain in a single thread

I am a new java socket developer. In my solution has three sockets for sending and receiving. I want to receive three socket's data in a single thread. For this reason, how i get notification which socket get data from remote.
Handling multiple streams (those of the sockets) within a single thread is possible. It requires the use of socket channels (from java.nio.channels) and of a (single) Selector.
You create a Selector and register the SocketChannels.
To learn about any new possibility for an i/o operation, you call the Selector's select() method, which returns whenever one of the channels is ready for reading, writing or accepting. You'll have to learn the ready channel (i.e., obtain its "key"), and call its appropriate data transfer method.
There is some sample code to be found on the net.
PS: It might be easier to use threads.

Must a listening socket runs in thread?

I have some problems understanding how a socket should be handled. I get that server socket must runs in its own thread, because it must check if there are new connections. Now, i'm not sure if every socket opened by a new connection should runs in a thread.
What i have in mind is checking every x time the socket states. If it has something to be read, then read. If not, check the next socket. I see some examples where this process is done in a thread, but i dont want a socket to do stuff, just want to read if it has some data, and process them.
The answer is no, you don't need to listen in a separate thread. But, just realize that while you are "listening" your entire program will be waiting for that to complete before moving onward.
So unless you are fine with your entire program waiting, I would suggest a separate thread.
You can also have one thread which communicates with all sockets in a round-robin manner. It checks each socket if it has new data, and when it hasn't it checks the next.
Another alternative is to use NIO (New Input/Output).
The idea behind NIO is that you have a thread with one Selector which owns multiple Channels (a channel can be a network socket or any other IO interface). You then call selector.select() in a loop. This method blocks until one or more channels have data, and then returns a set of these channels. You can then process the data the channels delivered.
Here is a tutorial.
The problems with round-robin using available() are many.
It assumes that available() actually works, which isn't guaranteed.
It assumes that all clients need the same amount of service.
N-1 clients wait while one client is serviced.
A non-responsive client can block not only your application but all the other clients.
I'm sure there are more.
Don't do this. Use threads or NIO.

Is dataInputStream of a Socket know how to deal with multiple writings to it?

I am developing a Net game, in general:
I have a server which launch a serverThread for each client that has connected to it.
Its purpose is to listen to messages from the specific client and to process it on the server.
Also for each client that is opened it launch a clientThread which is a listening thread to messages from the server.
The two threads are quite simple and similar threads which implements the Runnable Interface and therefore override the run method.
Each Run method is some kind of infinite loop that has on its start the command (blocking command):
int command = m_In.readInt();
and then do a process by switch cases structure over the received command.
after process was done, the loop cause the code to return to the blocking m_In.readInt()
To wait for another command to come.
My question is: My Net game has enough options which are using the communication over this m_In, so what happens if there are two messages or more coming almost together to the clientThread, how would the dataInputStream will act?
Will it begin to process first message and after its done will grab the second which is on some kind of a queue? or it could drop the second message and it will be lost?
Maybe that stream has buffer so it stores the second message in a queue or something?
Thanks
Streams by their nature expect data to come in a specified order. If you have two threads writing to the same stream at the same time, bad things will happen.
Now you can certainly synchronize access to the stream and have the two thread interleave their writing (so long as you build some sort of formatting on the stream that tells the receiver how to read data), but you don't get this by default.
Typically though, each client thread would have their own connection and thus their own stream to write into. A server can obviously read from multiple streams at the 'same time', and that is the normal server pattern.

Categories