Skip to content

Fix TCP client to detect connection closures #108

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Closed
wants to merge 5 commits into from
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
Expand Up @@ -51,9 +51,7 @@ protected Socket createSocket() {

@Override
public synchronized void sendMessage(String message) {
if (socket == null || socket.isClosed() || shouldConnect) {
connect();
}
checkConnection();

OutputStream os;
try {
Expand All @@ -65,13 +63,22 @@ public synchronized void sendMessage(String message) {
}

try {
// Write a space to the socket to verify connection before sending event
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I think this comment should include why we need this, rather what.

os.write(32);

os.write(message.getBytes());
} catch (Exception e) {
} catch (IOException e) {
shouldConnect = true;
throw new RuntimeException("Failed to write message to the socket.", e);
}
}

private void checkConnection() {
if (socket == null || socket.isClosed() || shouldConnect) {
connect();
}
}

@Override
public void close() throws IOException {
if (socket != null) {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -22,6 +22,7 @@

import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.net.ServerSocket;
import java.net.Socket;
import org.junit.Test;

Expand All @@ -45,7 +46,24 @@ protected Socket createSocket() {

String message = "Test message";
client.sendMessage(message);
client.close();

assertEquals(bos.toString(), message);
assertEquals(message, bos.toString().trim());
}

@Test(timeout = 5000)
public void testSendMessageWithSocketServer() throws IOException {
TCPClient client = new TCPClient(new Endpoint("0.0.0.0", 9999, Protocol.TCP));
ServerSocket server = new ServerSocket(9999);
client.sendMessage("Test message");
Socket socket = server.accept();

byte[] bytes = new byte[1024];
int read = socket.getInputStream().read(bytes);
String message = new String(bytes, 0, read);
socket.close();
server.close();

assertEquals("Test message", message.trim());
}
}