简体   繁体   中英

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

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM