gpt4 book ai didi

c - C 语言的服务器客户端聊天应用程序

转载 作者:行者123 更新时间:2023-11-30 20:59:36 25 4
gpt4 key购买 nike

我正在通过在客户端和服务器之间建立套接字连接来在客户端和服务器之间执行这个简单的聊天应用程序。但它正在无限循环中。谁能告诉我我犯了什么错误......

客户端代码

    int main(){

int client_socket = socket(AF_INET,SOCK_STREAM,0);
struct sockaddr_in server_address;
server_address.sin_family = AF_INET;
server_address.sin_port = htons(9002);
server_address.sin_addr.s_addr = INADDR_ANY;

int connection_status = connect(client_socket, (struct sockaddr*) &server_address, sizeof(server_address));

char server_response[256];
while(1){
read(client_socket, server_response, sizeof(server_response));
printf("Server:%s\n",server_response);
printf("Client:");
write(client_socket, server_response, sizeof(server_response));
if(strncmp("exit",server_response,4)==0){
printf("Server Exit Successful");
break;
}
}
close(client_socket);
return 0;
}

服务器代码

    int main(){

char server_message[256];

int server_socket = socket(AF_INET,SOCK_STREAM,0);

struct sockaddr_in server_address;
server_address.sin_family=AF_INET;
server_address.sin_port=htons(9002);
server_address.sin_addr.s_addr=INADDR_ANY;

bind(server_socket,(struct sockaddr*) &server_address, sizeof(server_address));

listen(server_socket,1);

int network_socket = accept(server_socket,NULL,NULL);
while(1){
write(network_socket,server_message,sizeof(server_message));
printf("Client:%s\n",server_message);
printf("Server:");
read(network_socket,server_message,sizeof(server_message));
if((strncmp(server_message,"exit",4))==0)
{
printf("Client Exit...\n");
break;
}
}
close(server_socket);

return 0;
}

最佳答案

我发现的一个问题是您没有为客户端提供连接地址。 INADDR_ANY 不会神奇地找到正确的服务器 IP 地址。当然,这不会导致无限循环,但会导致您的服务器永远监听它永远不会获得的连接,这可能看起来像无限循环。您的客户端将进入无限循环,因为您的循环是无限的,并且您在连接系统调用后没有检查错误。

关于c - C 语言的服务器客户端聊天应用程序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46732320/

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