网络通信 一、本地通信

本地通信编程模型:

进程A                        

                进程B

创建套接字(AF_LOCAL)

        创建套接字(AF_LOCAL)        

准备地址(sockadd_un)

        准备地址(sockadd_un)

绑定(自己的socket和地址)

        连接(connect,链接进程A的地址)

接收数据                                

        发送数据

关闭套接字                                

        关闭套接字

 

服务端实现代码:

#include <stdio.h>
#include <string.h>
#include <unistd.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <sys/un.h>
#define SOCK_FILE "/tmp/sock"

int main()
{
	//1.创建socket
	int sockfd = socket(AF_LOCAL,SOCK_DGRAM,0);
	if(0 > sockfd)
	{
		perror("socket");	
		return -1;
	}
	//2.准备地址
	struct sockaddr_un addr = {};
	addr.sun_family = AF_LOCAL;
	strcpy(addr.sun_path,SOCK_FILE);

	//3.绑定
	if(bind(sockfd,(struct sockaddr*)&addr,sizeof(addr)))
	{
		perror("bind");
		return -1;
	}

	//4.接收数据
	while(1)
	{
		char buf[1024] = {};
		int ret = recv(sockfd,buf,sizeof(buf),0);
		if(0 == strcmp(buf,"quit"))
		{
			printf("通信结束\n");
			break;
		}
		printf("read:%s\n",buf);	
	}
	
	//5.关闭socket
	close(sockfd);
	//6.删除临时文件
	unlink(SOCK_FILE);
	return 0;	
}

客户端实现代码:

#include <stdio.h>
#include <string.h>
#include <unistd.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <sys/un.h>

#define SOCK_FILE "/tmp/sock"

int main()
{
	//1. 创建socket
	int sockfd = socket(AF_LOCAL,SOCK_DGRAM,0);
	if(0 > sockfd)
	{
		perror("socket");
		return -1;
	}

	//2.准备地址
	struct sockaddr_un addr = {};
	addr.sun_family = AF_LOCAL;
	strcpy(addr.sun_path,SOCK_FILE);

	//3. 连接
	if(connect(sockfd,(struct sockaddr*)&addr,sizeof(addr)))
	{
		perror("bind");
		return -1;
	}

	//4. 发送数据
	while(1)
	{
		char buf[1024] = {};
		printf(">");
		gets(buf);
		send(sockfd,buf,sizeof(buf),0);
		if(0 == strcmp(buf,"quit"))
		{
			printf("通信结束\n");
			break;
		}
	}
	
	//5. 关闭套接字
	close(sockfd);
	return 0;	
}

 

上一篇:使用/dev/poll的str_cli函数


下一篇:网络通信 二、基于TCP协议的C/S模型