java - Synchronize on DataOutputStream -


I have gone through synchronization through so many tutorials that my head is spinning. I have never understood this fact: (.

I have a Java server ( main server ), when a customer connects to a new thread ( ClientThread ).

The client interacts with the ServerThread and ServerThread responses, each now and then the main server < / strong> will deliver a message to all customers who use DataTool's DataTut's DataOutputStream object.

I'm pretty sure That every now and then is my problem because both main server and ServerThread are trying to send something to the customer at the same time, so I have to lock the DataOutputstream object For my life I can not understand this concept further.

Send servertread to client method:

  Public Zero ReplyToOne ( String reply) {try {commandOut.writeUTF}; commandOut.flush ();} hold (IOException e) {logger.fatal ("r EplyToOne ", e); } logger.info (answer); }    

Distribute all client methods of the MainServer:

  Public static zero delivery (string broadcast message } {For (Map.Entry & lt; String, Object []> Entry: AccountEfileist. Entreset ()) {Object [] TMPOBAARA = EntryJet Value (); DataAutputstream temporarily = (DataOutputStream) TMPObject Array [INT_COMMAND_OUT]; // it can be obtained while the thread is using it {temporaryCOut.writeUTF (broadcast message); temporaryCOut.flush (); } Hold (IOE EXPRESS E) {Logger. Terror ("Distributed: to write", e); } logger.info (broadcast message); }}   

I think I should have something like this in my ServerThread class

  public synchronized data output stream getCommandOut () {return command-on; }   

Is this really simple? I know that it has been asked and answered, but I still can not find it without personal help.

If it were me .....

There will be one on the thread. Again, every time the client thread has a moment of laziness at the socket, it checks the queue if it has a message to send from the queue, then it sends it.

After that, the server, if needed, can add items to that line, and will be sent when there is some space in the connection.

Add to the queue, there is a method on ServerThread like this:

  addBroadcastMessage (MyData data) {broadcastQueue.add (data); }   

And then on the socket side, there is a loop on which there is a timeout block, so that it sits out of the socket if it is inactive, and then simply:

  while (! Broadcastkey.eaquality ()) {MyData data = broadcast field poll (); .... Send data ...}   

And you have done

Linkblocking will manage the Q locking and synchronization for you.

Comments

Popular posts from this blog

php - PDO bindParam() fatal error -

logging - How can I log both the Request.InputStream and Response.OutputStream traffic in my ASP.NET MVC3 Application for specific Actions? -

java - Why my included JSP file won't get processed correctly? -