[不懂就问] 为什么我的 socket 总是断断续续地出现 Connect failed

93 天前
 TimeNewRome
690 次点击
所在节点    问与答
3 条回复
TimeNewRome
93 天前
以下是 client 端代码:

void send(const std::string& message) {
int sock = socket(AF_INET, SOCK_STREAM, 0);
if (sock == -1) {
std::cerr << "Could not create socket" << std::endl;
return;
}

int sendBufferSize = 65536;
if (setsockopt(sock, SOL_SOCKET, SO_SNDBUF, &sendBufferSize, sizeof(sendBufferSize)) < 0) {
std::cerr << "Could not set send buffer size" << std::endl;
close(sock);
return;
}

sockaddr_in server;
server.sin_addr.s_addr = inet_addr("10.130.9.6");
server.sin_family = AF_INET;
server.sin_port = htons(8091);

if (connect(sock, (struct sockaddr *)&server, sizeof(server)) < 0) {
std::cerr << "Connect failed. Error" << std::endl;
close(sock);
return;
}

if (send(sock, message.c_str(), message.length(), 0) < 0) {
std::cerr << "Send failed" << std::endl;
}

close(sock);
}
TimeNewRome
93 天前
以下是 server 端代码:

int main() {
int server_fd, new_socket;
struct sockaddr_in address;
int addrlen = sizeof(address);
char buffer[32768] = {0};

if ((server_fd = socket(AF_INET, SOCK_STREAM, 0)) == 0) {
perror("socket failed");
exit(EXIT_FAILURE);
}

address.sin_family = AF_INET;
address.sin_addr.s_addr = INADDR_ANY;
address.sin_port = htons(8091);

if (bind(server_fd, (struct sockaddr *)&address, sizeof(address)) < 0) {
perror("bind failed");
close(server_fd);
exit(EXIT_FAILURE);
}

if (listen(server_fd, 3) < 0) {
perror("listen");
close(server_fd);
exit(EXIT_FAILURE);
}

while (true) {
if ((new_socket = accept(server_fd, (struct sockaddr *)&address, (socklen_t*)&addrlen)) < 0) {
perror("accept");
close(server_fd);
exit(EXIT_FAILURE);
}

int valread = read(new_socket, buffer, 1024);
if (valread > 0) {
std::cout << buffer << std::endl;
memset(buffer, 0, sizeof(buffer));
}

close(new_socket);
}

close(server_fd);
return 0;
}
TimeNewRome
93 天前
使用 perror 函数的输出结果是“Connect failed: Cannot assign requested address.”

这是一个专为移动设备优化的页面(即为了让你能够在 Google 搜索结果里秒开这个页面),如果你希望参与 V2EX 社区的讨论,你可以继续到 V2EX 上打开本讨论主题的完整版本。

https://www.v2ex.com/t/1067246

V2EX 是创意工作者们的社区,是一个分享自己正在做的有趣事物、交流想法,可以遇见新朋友甚至新机会的地方。

V2EX is a community of developers, designers and creative people.

© 2021 V2EX