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

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.

Related

thread safety of concurrent read and write on a socket

A tcp socket is an endpoint which has bidirectional read and write capabilities. In java we can aquire InputStream and OutputStream of the Socket.
is it safe to use those streams concurrently?
As far as i know there is a single connection that is capable to send or recieve from one endpoint to other data at any given time.
I'm implementing nio transport layer based on SocketChannels, and i want to keep one thread for all writes and one thread for accepting and reads, but i'm not sure what will happen if my threads concurrently try to read and write at the same time on the same socket...
As far as I know there is a single connection that is capable to send or recieve from one endpoint to other data at any given time.
Or both at the same time. It's a full-duplex connection. You can send and receive at the same time.

Is it possible to use multiple java ObjetOutputStream objects to write to a single java ObjectInputStream object?

I have a standard client/server setup.
The program I'd like to build acts a lot like a mail office(which is my Server). Multiple people (client with ObjectOutputStream) hand the office (server with the single ObjectInputStream) mail with an attached address and the office sends the mail where it is supposed to go. If possible, I'd like to have one ObjectInputStream in the server that blocks, waiting for "mail" to come in from any ObjectOutputStream, then sends the "mail" where it's supposed to go. This way I can just have one thread that is completely dedicated to receiving data and sending it.
I will have a thread for each person's client with their ObjectOutputStream, but would like to not also need a matching thread in the server to communicate with each person. I am interested in this idea because I find it excessive to build tons of threads to separately handle connections, when it's possible that a single thread will only send data once in my case.
Is this feasible? or just silly?
Use a JMS queue of Java Message Service, is the design pattern for this case.
http://en.wikipedia.org/wiki/Java_Message_Service
If you have in the server app just one instance of ObjectInputStream and you have many clients then this instance needs to be shared by all threads thus you need to synchronize the access to it.
You can read more here. Hope this helps.
OR
You can have a pool of ObjectInputStream instances and using a assignment algorithm like Round Robin (doc) you can return the same instance for each x order thread for example ... this will make the flow in the server app to be more paralleled
Your question doesn't make sense. You need a separate pair of ObjectInputStream and ObjectOutputStream per Socket. You also need a Thread per Socket, unless you are prepared to put up with the manifest limitations of polling via InputStream.available(), which won't prevent your reads from blocking. If you are using Object Serialization you are already committed to blocking I/O and therefore to a thread per Socket.

Java - Different socket for same TCP IP

I want to create different thread for read and write method by using socket.
I wonder should I use different socket or same socket to share for both thread?
If you're reading and writing to and from the same device/object, i'd use the same thread. This way you don't have it trying to read something when you haven't written to it yet. Doing multiple threads might cause a multitude of errors if you're not careful, such as nulls.
You can use the same socket to both read and write. Of course one of the 2 endpoints must open a server socket. Then you can have 1 thread blocked waiting for input data while another thread could output data when needed
1. Create One socket object.
2. Use any nos of threads to access this object, but do keep enough care to make the
write and read operations Thread-Safe.
3. Try using the ServerChannel and ServerSocketChannel from java.util.nio package, which is Asynchronous .

Listener for incoming messages

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.

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