• Socket编程, 在server端read()函数调用后显示错误:Transport endpoint is not connected (犯了低级错误)


     1 for(;;){
     2         socklen_t len = sizeof(client_address);
     3         connfd = accept(listenfd, (struct sockaddr *)&client_address, &len);
     4         if(connfd < 0){
     5             printf("accept error: %s
    ", strerror(errno));
     6         }
     7         printf("server get connection from %s
    ", inet_ntop(AF_INET, &client_address.sin_addr, buff, sizeof(buff)));
     8 
     9         if((n = read(listenfd, message, 1024)) == -1){
    10             printf("read error: %s
    ", strerror(errno));
    11             exit(1);
    12         }
    13         message[n] = '';
    14         printf("receive the message of client: %s
    ", message);
    15         close(connfd);
    16 
    17     }

          刚接触unix网络编程, 在进行简单的client/server通信时犯了低级错误, 上面的代码为server端的接收client链接请求并显示client传过来的信息, accept函数成功后返回一个内核生成的一个全新的描述符 赋值给connfd, 所以后面调用read()函数时, 第一个参数应该是connfd 而不是 listenfd。 所以代码第9行应该改为

            if((n = read(connfd, message, 1024)) == -1){ 

    附:

    int accept(int sockfd, struct sockaddr *cliaddr, socklen_t *addrlen);
    
    int read(int handle, void *buf, int nbyte);
  • 相关阅读:
    shell命令执行过程
    shell中的引用
    ansible小结
    centos自动化安装镜像制作
    centos kickstart
    centos内核引导参数
    C# .NET 遍历Json 形成键值对
    强大的Winform Chart图表控件使用说明
    C#实现转换十六进制
    C# 批量登陆远程目录
  • 原文地址:https://www.cnblogs.com/KarryWang/p/3199959.html
Copyright © 2020-2023  润新知