linux本地socket通信(学习笔记)

服务端

创建 socket
绑定 bind
监听 listen
等待连接 accept
接收客户端数据 read
发送数据 write

服务端代码

// server1.c
#include <stdio.h>
#include <stdlib.h>
#include <sys/socket.h>
#include <unistd.h>
#include <sys/un.h>
#include <sys/types.h>
#include <assert.h>
#include <string.h>

int main()
{
    unlink("socket_server");
    int server_sockfd = socket(PF_LOCAL, SOCK_STREAM, 0);
    assert(server_sockfd != -1);

    struct sockaddr_un address;
    address.sun_family = PF_LOCAL;
    address.sun_len = sizeof(address);
    strcpy(address.sun_path, "socket_server");

    int ret = bind(server_sockfd, (struct sockaddr *)&address, sizeof(address));
    assert(ret == 0);

    ret = listen(server_sockfd, 5);
    assert(ret == 0);

    struct sockaddr_un client_address;
    int len = sizeof(client_address);
    printf("accpet before...\n");
    int client_sockfd = accept(server_sockfd, (struct sockaddr *)&client_address, &len);
    assert(client_sockfd != -1);
    printf("accpet ok ...\n");

    char ch;
    ssize_t chars_read = read(client_sockfd, &ch, 1);
    assert(chars_read == 1);

    ch++;
    ssize_t chars_write = write(client_sockfd, &ch, 1);
    assert(chars_write == 1);

    close(client_sockfd);
    close(server_sockfd);

    return 0;
}

客户端

创建 socket
连接 connect
接收数据 read
发送数据 write

示例代码如下

// client1.c
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <sys/socket.h>
#include <sys/types.h>
#include <sys/un.h>
#include <string.h>
#include <errno.h>
#include <assert.h>

int main()
{
    int client_sockfd = socket(PF_LOCAL, SOCK_STREAM, 0);
    assert(client_sockfd != -1);

    struct sockaddr_un address;
    address.sun_family = PF_LOCAL;
    address.sun_len = sizeof(address);
    strcpy(address.sun_path, "socket_server");

    int ret = connect(client_sockfd, (struct sockaddr *)&address, sizeof(address));
    if (ret == -1)
    {
        perror("connect");
    }
    assert(ret == 0);

    char ch = 'A';
    ssize_t chars_write = write(client_sockfd, &ch, 1);
    assert(chars_write == 1);
    ssize_t chars_read = read(client_sockfd, &ch, 1);
    assert(chars_read == 1 && ch == 'B');

    printf("ch = %c\n", ch);

    close(client_sockfd);

    return 0;
}

先运行server,然后运行client, client发送一个字符‘A’,server接收到‘A’,回复一个字符’B‘,client接收到’B‘

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值