How can I simulate a Client-Server application using Java threads? - java

For this school assignment, I need to simulate a client server type application using Java threads (no need for sockets etc). How might I go about doing it?
I need a way to server to start and wait for clients to call it then it should return a response. The "API" in my mind was something like:
server.start()
client1.connect(server)
client2.connect(server)
x = client1.getData()
y = client2.getData()
success1 = client1.sendData(1)
success2 = client2.sendData(2)
How might the server|client.run method look like? Assume I could hardcode the method calls for now.

I suggest to use the following approach:
1. Have "server" code that works with Blocking Queue -
A blocking queue is a data structure which is synchronized and let's the thread that reads data from it (the "consumer" thread) to wait until there is a data in the queue to be read.
The "producer" thread is a thread that "pushes" data on the queue.
I would recommend you use one of the blocking queue implementations.
I would also suggest you read more about "consumer producer" pattern.
Blocking queue also eliminates the need for "busy wait" which is not recommended in multi-threading programming.

From the description that you have provided What i can suggest is you should write some thing like
1) Have one queue where all the clients can put up messages.
2) server which is running in an infinite loop like while(true) waits for the new messages that has been put in the queue and if it finds one then processes it and marks it as processed.
3) The job of the client threads would be to create messages and put them in the queue. And notifying the server that new message has been added to the queue so that server can come to know that new message has been arrived for processing.
For this program to make it working i think you need to learn Thread's notify, notifyAll(), and wait() methods. So basically without sockets what you are looking for it "Inter thread communication". This link can help.
Hope this helps.

Related

How to send messages to a temporal channel created in another handler?

Maybe there is some "integration-pattern" here I miss...
I have a proccess (a thread from an TaskExecutor) that is some cases need to stop and wait for an additional data to continue.
I was thinking about blocking in a receive method, but I don't find how to send, from a different thread a message to that channel (a temporal one, isn't it?) to unblock this thread, only this.
The component responsible about unblock should receive a message from some kind of messagin platform (redis,rabbit,...) and then "notify" the blocked execution.
An ugly implementation could be a wait/notify but of course I don't want to use that having a full "message-oriented" solution.
Is there any component/solution for this problem?
Maybe a subscriber with some topic I can use to be sure only that thead ir running again, but I cannot block in a publishsubscribe channel, can I?
thanks a lot,
that is some cases need to stop and wait for an additional data to continue.
Looks like this is indeed the use-case for the Thread Barrier component.
Another way to do something similar is an Aggregator for the releaseStrategy as 2 messages by size.
Anyway the correlationKey is a key entity in both use-cases.

Thread pool when serving multiple clients with blocking methods

I am developing a webserver in java that will provide websocket communication to its' clients. I have been proposed to use a thread pool when dealing with many clients because it is a lot more time efficient than to use one thread per client.
My question is simply, will Javas ExecutorService, newFixedThreadPool be able to handle a queue of runnable tasks with thread blocking methods being called inside of them?
In other words i guess i am wondering if this thread pool is asynchronous?
The reason i am asking is that i have tried using a newFixedThreadPool with, lets say, 2 threads. Then when i connect 3 clients to the server, i can only receive commands from the first two. But i guess i could be doing something wrong, thats why i am asking.
The runnable tasks are also in an infinite while loop (only ends when client disconnects).
Well, it depends on your implementation. The easiest case is having clients keeping their thread active until the disconnect (or get kicked out because of a timeout). In this case, your thread pool isn't very efficient. I'll only re-use disconnected users' threads instead of creating new one (which is good, but not really relevant).
The second case would be activating the threads only when needed (let's say when a client sends or receives a messages). In this case, you need to remember the server-side (keeping an id for example), in order to be able to sever the thread connection when they don't need them, and re-establish it when they do. In order to do that, you must keep the sockets somewhere, but unbound to any specific thread.
I actually didn't code that myself but I don't see why it would work as this is the mechanism used for websites (i.e. HTTP protocol)

How to have a run in an Service?

I have implemented an service that runs in a seperate process.
This service contains a separate thread where i have a socket connection.
This thread has a run() where it is continuously sending data to the port.
My problem is after triggering the run() in the thread i don't get any contact with it anymore, i can see in the program that have open the socket that it consciously sends the data but the idea was that i while it is running i could change data that it sends for an example time.
here is my run in the external thread:
public void run()
{
if(run)
{
// Team and player names message is sent when entering in a game
setBaseMessage();
SendMessageToCOMPort(base_message + CalculateCRC(base_message));
sleep(); // waits for 100 ms
}
}
Anyone have any idea what might be wrong ?
I did not quite get your problem. It seems that you want to run a separate thread in your service which does some socket communication. Furthermore you want to be able to influence the data the thread is sending using the socket.
I have implemented an service that runs in a seperate process.
First of all, android services aren't running in a separate process or thread by default. Therefore, to run long running operations you have to develop multithreading by your self using Java threading and implementing the run method as you have done it.
Threads of a single process share the same memory. Therefore, to influence what the socket thread is doing, you can use data structures like a queue or a list which are shared among the threads. For example, you could apply the producer-consumer pattern. The producer passes data to a shared queue. The consumer consumes the data from the queue and processes it. However, be aware that you have to synchronize the access to the shared queue.
I hope I was able to clarify the issue and give you some advice to solve the issue.

Java - networking - Best Practice - mixed synchronous / asynchronous commands

I'm developing a small client-server program in Java.
The client and the server are connected over one tcp-connection. Most parts of the communication are asynchronous (can happen at any time) but some parts I want to be synchronous (like ACKs for a sent command).
I use a Thread that reads commands from the socket's InputStream and raises an onCommand() event. The Command itself is progressed by the Command-Design-Pattern.
What would be a best-practice approach (Java), to enable waiting for an ACK without missing other, commands that could appear at the same time?
con.sendPacket(new Packet("ABC"));
// wait for ABC_ACK
edit1
Think of it like an FTP-Connection but that both data and control-commands are on the same connection. I want to catch the response to a control-command, while data-flow in the background is running.
edit2
Everything is sent in blocks to enable multiple (different) transmissons over the same TCP-Connection (multiplexing)
Block:
1 byte - block's type
2 byte - block's payload length
n byte - block's paylod
In principle, you need a registry of blocked threads (or better, the locks on which they are waiting), keyed with some identifier which will be sent by the remote side.
For asynchronous operation, you simply sent the message and proceed.
For synchronous operation, after sending the message, your sending thread (or the thread which initiated this) create a lock object, adds this with some key to the registry and then waits on the lock until notified.
The reading thread, when it receives some answer, looks in the registry for the lock object, adds the answer to it, and calls notify(). Then it goes reading the next input.
The hard work here is the proper synchronization to avoid dead locks as well as missing a notification (because it comes back before we added ourself to the registry).
I did something like this when I implemented the remote method calling protocol for our Fencing-applet. In principle RMI works the same way, just without the asynchronous messages.
#Paulo's solution is one I have used before. However, there may be a simpler solution.
Say you don't have a background thread reading results in the connection. What you can do instead do is use the current thread to read any results.
// Asynchronous call
conn.sendMessage("Async-request");
// server sends no reply.
// Synchronous call.
conn.sendMessage("Sync-request");
String reply = conn.readMessage();

Stateless Blocking Server Design

A little help please.
I am designing a stateless server that will have the following functionality:
Client submits a job to the server.
Client is blocked while the server tries to perform the job.
The server will spawn one or multiple threads to perform the job.
The job either finishes, times out or fails.
The appropriate response (based on the outcome) is created, the client is unblocked and the response is handed off to the client.
Here is what I have thought of so far.
Client submits a job to the server.
The server assigns an ID to the job, places the job on a Queue and then places the Client on an another queue (where it will be blocked).
Have a thread pool that will execute the job, fetch the result and appropriately create the response.
Based on ID, pick the client out of the queue (thereby unblocking it), give it the response and send it off.
Steps 1,3,4 seems quite straight forward however any ideas about how to put the client in a queue and then block it. Also, any pointers that would help me design this puppy would be appreciated.
Cheers
Why do you need to block the client? Seems like it would be easier to return (almost) immediately (after performing initial validation, if any) and give client a unique ID for a given job. Client would then be able to either poll using said ID or, perhaps, provide a callback.
Blocking means you're holding on to a socket which obviously limits the upper number of clients you can serve simultaneously. If that's not a concern for your scenario and you absolutely need to block (perhaps you have no control over client code and can't make them poll?), there's little sense in spawning threads to perform the job unless you can actually separate it into parallel tasks. The only "queue" in that case would be the one held by common thread pool. The workflow would basically be:
Create a thread pool (such as ThreadPoolExecutor)
For each client request:
If you have any parts of the job that you can execute in parallel, delegate them to the pool.
And / or do them in the current thread.
Wait until pooled job parts complete (if applicable).
Return results to client.
Shutdown the thread pool.
No IDs are needed per se; though you may need to use some sort of latch for 2.1 / 2.3 above.
Timeouts may be a tad tricky. If you need them to be more or less precise you'll have to keep your main thread (the one that received client request) free from work and have it signal submitted job parts (by flipping a flag) when timeout is reached and return immediately. You'll have to check said flag periodically and terminate your execution once it's flipped; pool will then reclaim the thread.
How are you communicating to the client?
I recommend you create an object to represent each job which holds job parameters and the socket (or other communication mechanism) to reach the client. The thread pool will then send the response to unblock the client at the end of job processing.
The timeouts will be somewhat tricky, and will have hidden gotcha's but the basic design would seem to be to straightforward, write a class that takes a Socket in the constructor. on socket.accept we just do a new socket processing instantiation, with great foresight and planning on scalability or if this is a bench-test-experiment, then the socket processing class just goes to the data processing stuff and when it returns you have some sort of boolean or numeric for the state or something, handy place for null btw, and ether writes the success to the Output Stream from the socket or informs client of a timeout or whatever your business needs are
If you have to have a scalable, effective design for long-running heavy-haulers, go directly to nio ... hand coded one-off solutions like I describe probably won't scale well but would provide fundamental conceptualizing basis for an nio design of code-correct work.
( sorry folks, I think directly in code - design patterns are then applied to the code after it is working. What does not hold up gets reworked then, not before )

Categories

Resources