unix domain socket 通信之c服务端python客户端通信

server:

#include 
#include 
#include 
// #include 
#include 
#include 
#include 
#define BUF_SIZE 10 /*MAXmum sizeof messages exchanged between client toserver*/

#define SV_SOCK_PATH "/tmp/ud_ucase"

int main(int argc, char *argv[])
{
    struct sockaddr_un svaddr,claddr;
    int sfd,j;
    ssize_t numBytes;
    socklen_t len;
    char buf[BUF_SIZE];

    sfd = socket(AF_UNIX,SOCK_DGRAM,0);      /*Create server socket*/
    if(sfd == -1)
    {
        perror("socket");
    }
    /*Construct well-known address and bind server socket to it*/
    if(remove(SV_SOCK_PATH)==-1 && errno !=ENOENT)
    {
        printf("remove -%s",SV_SOCK_PATH);
    }
    memset(&svaddr,0,sizeof(struct sockaddr_un));
    svaddr.sun_family = AF_UNIX;
    strncpy(svaddr.sun_path,SV_SOCK_PATH,sizeof(svaddr.sun_path)-1);

    if(bind(sfd,(struct sockaddr *)&svaddr,sizeof(struct sockaddr_un)) ==-1)
    {
        perror("bind");
    }
    for(;;)
    {
        len = sizeof(struct sockaddr_un);
        numBytes = recvfrom(sfd,buf,BUF_SIZE,0,(struct sockaddr *)&claddr,&len);
        if(numBytes == -1)
        {
            perror("recvfrom");
        }
        printf("Server received %ld bytes from %s\n",(long)numBytes,claddr.sun_path);
        for(j=0;j<numBytes;j++)
        {
            buf[j] = toupper((unsigned char)buf[j]);
        }
        if(sendto(sfd,buf,numBytes,0,(struct sockaddr *)&claddr,len) != numBytes)
        {
            perror("sendto");
        }
    }
}

client:

import os
import socket
import argparse

# 定义常量
BUF_SIZE = 10
SV_SOCK_PATH = "/tmp/ud_ucase"
CL_SOCK_PATH = "/tmp/ud_ucase_cl"


# 定义主函数
def main():
    parser = argparse.ArgumentParser(description='Send messages to a Unix domain socket server.')
    parser.add_argument('msg', metavar='msg', type=str, nargs='+')
    args = parser.parse_args()
    # 创建客户端套接字
    sfd = socket.socket(socket.AF_UNIX, socket.SOCK_DGRAM)

    # 绑定客户端套接字到路径(基于PID)
    client_addr = CL_SOCK_PATH
    sfd.bind(client_addr)

    # 构造服务器地址
    server_addr = SV_SOCK_PATH

    try:
        # 向服务器发送消息并接收响应
        for msg in args.msg:
            # 发送消息到服务器
            sfd.sendto(msg.encode(), server_addr)

            # 接收响应
            resp, addr = sfd.recvfrom(BUF_SIZE)
            print('response {}: {}'.format(len(resp), resp))
    finally:
        # 关闭套接字并删除客户端套接字路径
        sfd.close()
        try:
            os.remove(client_addr)
        except OSError:
            pass
        exit(0)


if __name__ == '__main__':
    main()

效果如下:
unix domain socket 通信之c服务端python客户端通信_第1张图片
unix domain socket 通信之c服务端python客户端通信_第2张图片

你可能感兴趣的:(unix,c语言,python)