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

I am developing a small client-server program in Java.

The client and server are connected through one tcp connection. Most parts of the message are asynchronous (this can happen at any time), but some parts I want to be synchronous (for example, the ACK for the command sent).

I use Thread, which reads commands from the InputStream socket and raises the onCommand () event. The team itself is being promoted using Command-Design-Pattern.

What would be the best practice (Java) approach to enable ACK expectation without any other commands that might appear at the same time?

con.sendPacket(new Packet("ABC")); // wait for ABC_ACK 

edit1

Think of it as an FTP connection, but both the data and the management commands are in the same connection. I want to catch a response to a control command while a data stream is running in the background.

edit2

Everything is sent in blocks to enable several (different) transmissions on the same TCP connection (multiplexing)

 Block: 1 byte - block type 2 byte - block payload length n byte - block paylod 
+6
source share
2 answers

Basically, you need a registry of blocked threads (or, better, the locks on which they are waiting), with a key with some identifier that will be sent by the remote side.

For an asynchronous operation, you just sent a message and continue.

For synchronous operation, after sending a message, the send thread (or the thread that initiated it) creates a lock object, adds it with some key to the registry, and then waits for a lock until notification.

The read stream, when it receives any response, looks at the lock object in the registry, adds a response to it, and calls notify() . He then reads the next input.

The hard work here is the correct synchronization to avoid deadlocks, as well as the lack of notification (because it returns before we add ourselves to the registry).

I did something similar when I applied the remote method invocation protocol for the Fencing- applet. Basically, RMI works the same way, just without asynchronous messages.

+4
source

@ Paulo's solution is the one I used before. However, there may be a simpler solution.

Suppose you do not have data to read background threads in a connection. Instead, you can use the current stream to read any results.

 // Asynchronous call conn.sendMessage("Async-request"); // server sends no reply. // Synchronous call. conn.sendMessage("Sync-request"); String reply = conn.readMessage(); 
+1
source

Source: https://habr.com/ru/post/889786/


All Articles