我试图从一台计算机上的C++客户端向另一台计算机上的Python服务器发送一个字符串。
我的错误是send: Bad file descriptor
如果客户端与Python服务器联系,但它不接收字符串,则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;
}更新:
在客户端,在sock = socket...前面有一个没有必要的sock = socket...。
我删除了它,现在当我发送读取.的字符串时,服务器端出现了错误。
$ 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发布于 2022-02-01 00:26:10
在sock循环中重新声明for变量,因此调用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);所以它给出了外部变量。
https://stackoverflow.com/questions/70933676
复制相似问题