Client/server application. Multiple clients can connect to the server. For each client connection the server creates new thread. The client sends data until it closes socket. So I need that the data, managed by the thread server, should be returned to the main server every time. I can't wait that the thread finishes his job, because i don't know when the client closes connection. What are the right methods?
Asked
Active
Viewed 114 times
0
-
You need something like `C#`'s `yield return`. Try this link - http://stackoverflow.com/questions/1980953/is-there-a-java-equivalent-to-cs-yield-keyword – TDG Jul 03 '15 at 09:28
-
You can call a method on the main server and pass the Information. So the main server can read this Information in it's own fields – red13 Jul 03 '15 at 09:41
-
What do you mean, "the main server?" Aren't you talking about threads that run _in_ the server? I think that if you can better define what "retuned to the main server" means, then the answer to your question probably will become obvious. – Solomon Slow Jul 03 '15 at 10:04
-
The main (thread) server creates new threads. For example the server loop forever until a client connect to it, the server creates new thread for this client. The thread take data from the client and it want to show these data to the server in a GUI. Repeat this action with many client. – kabal Jul 03 '15 at 15:04
1 Answers
0
When creating a thread you can pass a shared queue as a parameter. In the thread's body, when you get the data from client, push it to the queue. In your server loop poll the data from the queue and use it. ConcurrentLinkedQueue should be suitable. Example:
// main server thread
Queue<SomeData> queue = new ConcurrentLinkedQueue<>();
// ... loop code, etc
Thread thread = new MyThread(queue);
// in thread responsible for GUI updates
SomeData data = queue.poll();
if (data != null) // do something
// client connection thread
SomeData data = ... // received from client
queue.offer(data);

AlmasB
- 3,377
- 2
- 15
- 17
-
The problem here is that the data update is possible only when the server gets a client connection, because it waits in the ServerSocket.accept() method. – kabal Jul 04 '15 at 08:22
-
Hence you need another thread responsible for data updates because accept() blocks the thread in which it is executed. Spawn a thread to do updates to GUI and only then start listening for connections – AlmasB Jul 04 '15 at 09:24