0

I am trying to implement a client-server application. Suppose i have two files, Server.java and Client.java. I am connected with both via DataOutputStream and DatainputStream and through socket programming. The clients have multi-threading implemented in Server.java.

Now the Server.java is doing a write.utf() to write a question to the Client.java, and the Client.java, in its terminal, is implementing a readUTF() and uses the Scanner class to get input from user keyboard.

Suppose now there is another client thread that wants to broadcast a message to all other clients. How would i stop/pause/lock the Scanner in the Client console to do a writeUTF() to the Client console to broadcast the message? The client should be able to resume its activity after the message is broadcasted.

Harris
  • 89
  • 1
  • 7

1 Answers1

0

One possible solution is to use a Queue. As you read in from the Scanner, messages can be placed in the Queue until they are sent out. When a broadcast needs to be made, it can be placed on the Queue (or perhaps on multiple queues depending on the situation). Just be sure that if you have multiple threads accessing a Queue, you are putting it in a synchronized block of code.

In a client-server situation, a LinkedBlockingQueue may be of use, as this will allow you to read from the Queue forever, and when it is empty, the client or server will simply wait for the Queue to get another item without any constant checking on your part.

Unsolved Cypher
  • 1,025
  • 10
  • 24
  • Hi i think i was looking for how to broadcast the message to the client when the client is at `System.in`. So when the message is broadcasted, the client currently only receives it after inputting the scanner. I want to know would there be a way to, in a way, do a `writeToUTF()` again to the client. – Harris Nov 18 '19 at 12:13
  • Sorry if I misunderstood. So what you want to do is wait for the user to finish their input into the Scanner and hit enter, and only then receive the broadcast? – Unsolved Cypher Nov 18 '19 at 19:09
  • So while the scanner waits for the user to finish the input into the scanner, the message needs to be broadcasted even though 'readUTF()' has not received an input from the scanner. – Harris Nov 19 '19 at 04:18