C中的Server Client Chat应用程序

时间:2017-10-13 14:33:56

标签: c sockets networking

我在一个客户端和一个服务器之间通过建立它们之间的套接字连接来做这个简单的聊天应用程序。但是它进入无限循环。任何人都可以说我做错了什么......

客户代码

    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;
     }

1 个答案:

答案 0 :(得分:1)

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