首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >Sockets_Client_Server_communication_Linux_C

Sockets_Client_Server_communication_Linux_C
EN

Stack Overflow用户
提问于 2015-02-26 18:17:47
回答 1查看 41关注 0票数 0

嗨,今天我试着学习c和Linux中的套接字通信,但是我下面的代码并不像预期的那样工作。虽然我知道错误发生在哪里,但我还是找不到问题。

server.c

代码语言:javascript
复制
#include <sys/types.h>
#include <sys/socket.h>
#include <sys/un.h>
#include <stdio.h>
#include <stdlib.h>
#include<string.h>

char data[100];

int main()
{
    int socket_descrp,server_len;
    socket_descrp = socket(AF_UNIX,SOCK_STREAM,0);
    if(socket_descrp<0)
    {
     perror("server Socket failed\n");
     exit(1);
     }

    struct sockaddr_un server,client; 
    int clientlen;
    server.sun_family = AF_UNIX;
    strcpy(server.sun_path,"mysocket");
    unlink("mysocket");
    server_len = sizeof(server);

    if(bind(socket_descrp,(struct sockaddr *)&server,server_len)<0){
        printf("bind error\n");
        exit(1);

    }

    if(listen(socket_descrp,1)<0)
    {
        printf("listen error\n");
        exit(1);
    }

    if(accept(socket_descrp,(struct sockaddr*)&client,&clientlen)<0)
    {
        printf("accept error\n");
        exit(1);
    }



    if(read(socket_descrp,data,99)<0)
    {
        perror("Error occured in reading\n");
        exit(1);
    }
    else if(read(socket_descrp,data,99)==0)
    {
        printf("No bytes are read\n");
        exit(1);
    }
    else
        printf("Reading from client\n");

    printf("The read content is: %s\n",data);



    close(socket_descrp);   
    return 0;

}

client.c

代码语言:javascript
复制
#include <sys/types.h>
#include <sys/socket.h>
#include <sys/un.h>
#include <stdio.h>
#include <stdlib.h>
#include<string.h>

char data[100]="Hello World!";

int main()
{
    int socket_descrp,client_len;
    socket_descrp = socket(AF_UNIX,SOCK_STREAM,0);
    if(socket_descrp<0)
    {
     perror("client Socket failed\n");
     exit(1);
     }

    struct sockaddr_un client;

    client.sun_family = AF_UNIX;
    strcpy(client.sun_path,"mysocket");
    client_len = sizeof(client);

    if(connect(socket_descrp,(struct sockaddr*)&client,client_len)<0)
    {
     printf("Connection error\n");
     exit(1);
    }

    if(write(socket_descrp,data,strlen(data))<0)
    {
        printf("Error writing to the socket\n");
        exit(1);
    }

    return 0;

}

打印的错误消息是服务器可执行文件上的“读取错误:无效参数”。我不明白为什么它不识字。客户端可执行文件没有打印任何错误消息。我花了将近两个小时来寻找问题。:(

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2015-02-26 18:33:57

无法从服务器套接字读取。accept返回要通过以下方式进行通信的套接字:

代码语言:javascript
复制
    client_sock = accept(socket_descrp, ...);
    read(client_sock, ...);
票数 2
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/28749853

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档