I've written a TCP socket in C that connects to port 5678. It is supposed to transmit a String from C to a TCP client written in Python.
Here's the server loop written in C:
for(;;) {
bzero(buffer, 256);
// Socket read functions
n = read(clientsockfd, buffer, 255);
if (n == 0) {
printf("[Socket]: Client disconnected\n");
break;
}
if (n < 0) {
error("[Socket]: Error: Cannot read from socket\n");
}
// Socket write functions
printf("[Socket]: Sent: %s\n", "Some message!");
n = write(clientsockfd, "Some message!", 0);
if (n < 0) {
error("[Socket]: Error: Cannot write to socket\n");
}
}
My Python client connects to the TCP socket:
try:
sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
sock.connect(("localhost", 5678))
except socket.error: # Connection refused error
logging.critical("Could not connect to the socket!")
Then the client enters an infinite loop requesting data, receiving data, and printing the data:
while True:
sock.send(str(0).encode('utf-8'))
print(sock.recv(1024).decode('utf-8')))
But the Python client hangs on the recv() method.
I imagine this is a problem with the C server since I previously had a server written in Python and the client worked just fine.
Also, when debugging in telnet, the server has the expected behavior:
telnet localhost 5678
Any help with this issue would be greatly appreciated! Thanks!