gpt4 book ai didi

c++ - 客户端/服务器 C++ 之间的通信问题

转载 作者:行者123 更新时间:2023-11-28 07:39:41 26 4
gpt4 key购买 nike

我有一个 client(c++)/server(c) 程序,目前我很难在它们之间进行通信(我看不到客户端在服务器上说了什么,反之亦然)。我也在尝试让这个项目多线程化,或者至少接受来自客户端的多个连接。非常感谢所有帮助这里是与聊天有关的代码,您可以完整查看它 here

客户:

    recv(sockfd , server_reply , 2000 , 0);

puts("Enter message :"); // asking for password
scanf("%s" , message);
send(sockfd , message , strlen(message) , 0);

recv(sockfd, server_reply, 2000, 0);
//Receive a reply from the server
if( recv(sockfd , server_reply , 2000 , 0) < 0)
{
puts("recv failed");
}

while( (read_size = recv(nsockfd , server_reply , 4000 , 0)) != 0)
{

puts("Enter message :"); // asking for password
scanf("%s" , message);
send(sockfd , message , strlen(message) , 0);

recv(sockfd, server_reply, 2000, 0);


}

服务器

      char client_address[90];
sprintf(client_address, "Welcome %s", inet_ntoa(addr_remote.sin_addr));

char welc_msg[90] = "Welcome %s";
char friend_msg[50] = "Hello little friend \n";
char username[30] = "Enter user:";
char pass[30] = "Enter pass: ";

write(nsockfd , client_address , strlen(client_address)); // attempting to send client "Hello, (their ip address)"
read_size = recv(nsockfd , client_message , 4000 , 0);

read_size = recv(nsockfd , client_message , 4000 , 0);
printf( "%s", client_message);
printf( "\n");



//Receive a message from client
while( 1 ) // while( (read_size = recv(nsockfd , client_message , 4000 , 0)) != 0)
{
//clearing buffer
memset(client_message, 0, sizeof(client_message));

//taking received message and printing it
read_size = recv(nsockfd , client_message , 4000 , 0);
printf( "%s", client_message);
printf( "\n");

//Send the message back to client
// write(nsockfd , server_message , strlen(server_message));


if (strcmp(client_message , "Hello")) // condition for project
{
write(nsockfd, friend_msg, strlen(friend_msg));
}

}

最佳答案

调用系统函数时,一定要检查错误!在相关的地方,还要检查部分写入/接收。例如,当您有此行时:

send(sockfd , message , strlen(message) , 0);

你应该有这样的东西(未经测试,所以自己想一想):

(编辑:删除了不必要的重新发送循环以简化代码。如果您想查看编辑历史记录...)

int msglen = strlen(message);
fprintf(stderr, "debug: about to send %d bytes", msglen);

int sent = send(sockfd , message , msglen , 0);

if (sent == -1) { // for each function, read docs for error result
perror("send message");
// do some error handling
} else if (sent < msglen) {
fprintf(stderr, "debug: partial send %d/%d\n", sent, msglen);
// do some disconnect handling
}

一旦你有正确的错误报告,如果你不能解决你的问题,然后用这个调试/错误信息更新问题。

关于c++ - 客户端/服务器 C++ 之间的通信问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16099750/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com