unix socket通信的方式

前端之家收集整理的这篇文章主要介绍了unix socket通信的方式前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。

unix socket


#include "sys/un.h"
#include "netinet/in.h"
#include "sys/socket.h"
#include <sys/types.h>
#include <unistd.h>
#include <sys/time.h>
#include "string.h"
#include "pthread.h"
#include <stdio.h>
#include <unistd.h>
#include <stdlib.h>
#include <string.h>

#define LISTEN_PATH "/data/test_socket"
static int  listenFd = 0;

int init()
{
    int  rcv_len;
    int on=1;
    struct sockaddr_un servAddr;
    unlink(LISTEN_PATH);
    INFO("init");
    servAddr.sun_family = AF_UNIX;
    strcpy(servAddr.sun_path,LISTEN_PATH);
    if((listenFd = socket(AF_UNIX,SOCK_DGRAM,0)) < 0) {
        INFO("%s",strerror(errno));
        return -1;
    }
    if((setsockopt(listenFd,SOL_SOCKET,SO_REUSEADDR,&on,sizeof(on)))<0) {
        INFO("%s",strerror(errno));
        return -1;
    }
    if(::bind(listenFd,(struct sockaddr*)&servAddr,sizeof(servAddr)) < 0){
        close(listenFd);
        INFO("%s",strerror(errno));
        return -1;
    }
    INFO("listenfd %d",listenFd);
    return 0;
}

bool Start_Server()
{
	init();
	int rcv_len;
	const int BUFSIZE = 1024*1024;
	while(true) {
				char *socket_buf = (char *)malloc(BUFSIZE);
				fd_set rs;
				FD_ZERO(&rs);
				FD_SET(listenFd,&rs);
				int res = select(listenFd + 1,&rs,NULL,NULL);
				if (FD_ISSET(listenFd,&rs)) {
					if((rcv_len = recvfrom(listenFd,socket_buf,BUFSIZE,NULL)) > 0) {
						//memcpy(buf,rcv_len);
						INFO( "live_play_add_ts_data------------->>>>>>>>>>>> dataSize = %d\n",rcv_len);
			            int ret = live_play_add_ts_data((unsigned char*)socket_buf,rcv_len);
						free(socket_buf);
						continue;
					}
					INFO("recvfrom waitEvent: %d",listenFd);
				}
    }
    free(socket_buf);
	return true;
}
		


client端的代码是:

#include "sys/un.h"
#include "netinet/in.h"
#include "sys/socket.h"

const char *LOCAL_SOCKET_PATH = "/data/test_socket";

int     local_socket;

int main(int argc,char *argv[])
{

   local_socket = socket(AF_UNIX,0);
   if (local_socket < 0) {
	printf("create local socket fail");
   }
	
    struct sockaddr_un servaddr;
    socklen_t socklen = sizeof(struct sockaddr_un);
    memset(&servaddr,sizeof(servaddr));

    servaddr.sun_family = AF_UNIX;
    strcpy(servaddr.sun_path,LOCAL_SOCKET_PATH);
	sendto(local_socket,buf,data_len,(struct sockaddr*)&servaddr,socklen);
	

    return 0;
}
原文链接:https://www.f2er.com/bash/389807.html

猜你在找的Bash相关文章