使用套接字将字符串从一台计算机上的 C++ 客户端发送到另一台计算机上的 Python 服务器。获取`发送:错误的文件描述符`

Using sockets to send a string from a C++ client on one computer to a Python server on another. Getting `send: Bad file descriptor`

我正在尝试将字符串从一台计算机上的 C++ 客户端发送到另一台计算机上的 Python 服务器。
我的错误是 send: Bad file descriptor

如果客户端联系 Python 服务器但未收到字符串,则服务器将被终止。虽然 Python 服务器是 运行,但当我尝试从 C++ 客户端发送字符串时,它确实会结束程序。所以我知道当我执行它时客户端正在访问服务器。

我可以使用 Python 客户端脚本从 C++ 客户端计算机向服务器发送字符串。由于这不是服务器的基本问题,我认为 this 和其他答案不适用于我的问题。

在 Python 脚本中,我尝试更改此数字。 s.listen(11)

这是Python服务器

import os
import sys
import socket

s=socket.socket()

host='192.168.0.101'
port=12003

s.bind((host,port))
s.listen(11)

while True:
    c, addr=s.accept()
    content=c.recv(1024).decode('utf-8')
    print(content)
    if not content:
        break

这是 C++ 客户端

#include <stdio.h>
#include <stdlib.h>
#include <sys/socket.h>
#include <sys/types.h>
#include <netdb.h>
#include <unistd.h>
    
#define ADDR "192.168.0.101"
#define PORT "12003"
    
void sendall(int socket, char *bytes, int length)
{
    int n = 0, total = 0;
    while (total < length) {
        n = send(socket, bytes + total, total-length, 0);
        if (n == -1) {
            perror("send");
            exit(1);
        }
        total += n;
    }
}
    
int main()
{
    struct addrinfo hints = {0}, *addr = NULL;
    hints.ai_family = AF_UNSPEC;
    hints.ai_socktype = SOCK_STREAM;
    
    int status = getaddrinfo(ADDR, PORT, &hints, &addr);
    if (status != 0) {
        fprintf(stderr, "getaddrinfo()\n");
        exit(1);
    }
    int sock = -1;
    {
        struct addrinfo *p = NULL;
        for (p = addr; p != NULL; p = addr->ai_next) {
            int sock = socket(p->ai_family, p->ai_socktype, p->ai_protocol);
            if (sock == -1) {
                continue;
            }
            if (connect(sock, p->ai_addr, p->ai_addrlen) != -1) {
                break;
            }
            close(sock);
        }
        if (p == NULL) {
            fprintf(stderr, "connect(), socket()\n");
            exit(1);
        }
        freeaddrinfo(addr);
        /* Do whatever. */
        sendall(sock, "Hello, World", 12);
    
        /* Do whatever. */
    }
    
    close(sock);
    return 0;
}

更新:
在client里面sock = socket...

前面有个不重要的int

我删除了它,现在我在发送读取的字符串时在服务器端收到错误..

$ python server.py

Traceback (most recent call last):
  File "/home/computer/server.py", line 35, in <module>
    content=c.recv(1024).decode('utf-8')
UnicodeDecodeError: 'utf-8' codec can't decode byte 0xfc in position 29: invalid start byte

您在 for 循环中重新声明了 sock 变量,因此当您调用 sendall()sock 的值是原来的 -1 .变化

            int sock = socket(p->ai_family, p->ai_socktype, p->ai_protocol);

            sock = socket(p->ai_family, p->ai_socktype, p->ai_protocol);

所以它分配了外部变量。