20
20
import java .io .OutputStream ;
21
21
import java .net .InetSocketAddress ;
22
22
import java .net .Socket ;
23
+ import java .util .LinkedList ;
23
24
import lombok .extern .slf4j .Slf4j ;
24
25
25
26
/** A client that would connect to a TCP socket. */
@@ -29,6 +30,8 @@ public class TCPClient implements SocketClient {
29
30
private final Endpoint endpoint ;
30
31
private Socket socket ;
31
32
private boolean shouldConnect = true ;
33
+ private final LinkedList <String > retryQueue = new LinkedList <>();
34
+ private String lastMessageSent ;
32
35
33
36
public TCPClient (Endpoint endpoint ) {
34
37
this .endpoint = endpoint ;
@@ -51,27 +54,45 @@ protected Socket createSocket() {
51
54
52
55
@ Override
53
56
public synchronized void sendMessage (String message ) {
54
- if (socket == null || socket .isClosed () || shouldConnect ) {
55
- connect ();
56
- }
57
+ checkConnection ();
57
58
58
59
OutputStream os ;
59
60
try {
60
61
os = socket .getOutputStream ();
61
62
} catch (IOException e ) {
62
63
shouldConnect = true ;
64
+ retryQueue .add (message );
63
65
throw new RuntimeException (
64
66
"Failed to write message to the socket. Failed to open output stream." , e );
65
67
}
66
68
67
69
try {
70
+ while (!retryQueue .isEmpty ()) {
71
+ String retryMessage = retryQueue .peek ();
72
+ os .write (retryMessage .getBytes ());
73
+ retryQueue .pop ();
74
+ }
75
+
68
76
os .write (message .getBytes ());
69
- } catch (Exception e ) {
77
+ lastMessageSent = message ;
78
+ } catch (IOException e ) {
79
+ // For broken pipe exception, retry last sent message
80
+ if (e .getMessage ().contains ("Broken pipe" )) {
81
+ retryQueue .add (lastMessageSent );
82
+ }
83
+
70
84
shouldConnect = true ;
85
+ retryQueue .add (message );
71
86
throw new RuntimeException ("Failed to write message to the socket." , e );
72
87
}
73
88
}
74
89
90
+ private void checkConnection () {
91
+ if (socket == null || socket .isClosed () || shouldConnect ) {
92
+ connect ();
93
+ }
94
+ }
95
+
75
96
@ Override
76
97
public void close () throws IOException {
77
98
if (socket != null ) {
0 commit comments