c - Sockets_Client_Server_communication_Linux_C

标签 c sockets

您好,今天我尝试学习 c 和 Linux 中的套接字通信,但我的以下代码没有按预期工作。尽管我知道错误发生的位置,但我找不到问题。

服务器.c

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

}

客户端.c

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

}

在服务器可执行文件上打印的错误消息是“读取时发生错误:参数无效”。我不明白为什么它不能读取。 客户端可执行文件未打印任何错误消息。我花了将近 2 个小时试图找到问题所在。 :(

最佳答案

您不能从服务器套接字读取。 accept 返回一个套接字以通过以下方式进行通信:

    client_sock = accept(socket_descrp, ...);
    read(client_sock, ...);

关于c - Sockets_Client_Server_communication_Linux_C,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28749853/

相关文章:

c - 使用GDB调试时如何打印指针指向的字符串?

Java套接字编程。如何在后台等待服务器响应?

c++ - 如何获得套接字的响应?

java - 为什么不创建单独的线程?

c - SIGIO从不开火

使用 eclipse 在 Windows 上用 C 语言编写一个简单的 GTK GUI

断开连接后C STREAM客户端套接字重用

python - 使用 -lwiringPy 在 C 中编译 Python 模块

c - 在 MSVC 2010 命令行中强制进行 32 位编译

sockets - MSG_WAITALL与SO_RCVTIMEO结合使用?