Java - Different socket for same TCP IP - java

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 .

Related

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

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.

Array of Sockets

I had a quick question on how i would maintain a connection of 1000 sockets. Im using threads to initiate writing and reading of the streams.
However when I pass the socket to the new thread, the thread won't exit after excecution. I wanted to know if passing the socket would keep the thread on because it was still connected.
I wanted to know if passing the socket would keep the thread on because it was still connected.
No. It won't do that.
Your threads are failing to exit for some other reasons. Possibly they are blocked in some operation on their respective sockets. Or maybe they are exiting, but you are expecting the threads or sockets to be magically removed from some array or list. (They won't be.)
I'd need some code, etc to give you a better explanation of what might be happening.

Categories