I am trying to build a sample TCP Forwarder. Here is the functionality in brief:
- The forwarder will listen at a given port.
- It contains a map of clients to servers
- Clients will connect to the forwarder and the forwarder will lookup the map and create a 2-way-forwarding-connection.
- To achieve this, it creates two threads per client.
- Thread 1: reads from the client and writes to the target server
- Thread 2: reads from the target server and write to the client.
All this is written in C. The Client and Target servers can be written in any language, right now its Java.
When I run a client for the first time, it works as expected. However, if I kill the client and restart it, the server never receives the new connection.
Here is my server code which I suspect is fault.
Socket clientSocket = serverSocket.accept();
InputStream inputStream = clientSocket.getInputStream();
OutputStream outputStream = clientSocket.getOutputStream();
while (true) {
byte[] bArray = new byte[2048];
try {
System.out.println(String.format("SERVER:%s: Attempting to read", this.name));
inputStream.read(bArray);
System.out.println(String.format("SERVER:%s: Received %s", this.name, new String(bArray)));
byte[] bytes = (name + ":" + counter).getBytes();
counter++;
outputStream.write(bytes);
System.out.println(String.format("SERVER:%s: Sent %s", this.name, new String(bytes)));
} catch (IOException e) {
System.out.println(String.format("SERVER:%s: Client Disconnected ", this.name));
clientSocket = serverSocket.accept();
inputStream = clientSocket.getInputStream();
}
}
In the C program, I detect the disconnection and close the socket as shown below:
LOGINFO("Reading from Client Socket.");
iResult = read(readSocket, buff, recvbuflen);
if (iResult <= 0) {
LOGERROR("Receiving failed");
close(readSocket);
break;
}