简体   繁体   中英

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!

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

这将写入零字节的数据。

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 .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM