James Taylor
James Taylor

Reputation: 6258

Writing into a TCP socket from C to Python

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!

Upvotes: 1

Views: 926

Answers (2)

Prabhu
Prabhu

Reputation: 3541

But the Python client hangs on the recv() method.

This is because the socket is blocking and you aren't receiving anything from the server.

There is nothing from the server because:

write(clientsockfd, "Some message!", 0);

You are asking zero bytes to be written to the socket.

write prototype is:

ssize_t write(int fd, const void *buf, size_t count);

write() writes up to count bytes from the buffer pointer buf to the fd.

Upvotes: 3

David Schwartz
David Schwartz

Reputation: 182743

n = write(clientsockfd, "Some message!", 0);

This writes zero bytes of data.

Upvotes: 2

Related Questions