linux学习笔记16 本地套接字进程间通信

本地套接字通信服务器端

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

using namespace std;

int main()
{
	int lfd=socket(AF_LOCAL, SOCK_STREAM, 0);
	int cfd;
	
	unlink("server.socket");	

	struct sockaddr_un ser_addr;
	ser_addr.sun_family=AF_LOCAL;
	strcpy(ser_addr.sun_path, "server.socket");
	bind(lfd, (struct sockaddr *)&ser_addr, sizeof(ser_addr));
	
	listen(lfd, 20);

	struct sockaddr_un cli_addr;
	socklen_t cli_addr_len;
	cfd=accept(lfd, (struct sockaddr *)&cli_addr, &cli_addr_len);
	if (cfd==-1)
	{
		cout<<"accept is error!\n";
		exit(1);
	}

	while (1)
	{
		char buf[256];
		char response[]="receive buf!\n";

		int n=read(cfd, buf, sizeof(buf));
		if (n==-1)
		{
			cout<<"read is error!\n";
			exit(1);
		}
		else if (n==0)
		{
			close(cfd);
			cout<<"client is closed\n";
			break;
		}
		else
		{
			cout<<buf<<endl;
			write(cfd, response, strlen(response));
		}
	}
		close(lfd);
		return 0;	
}

本地套接字客户端

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

using namespace std;

int main()
{
	int cfd=socket(AF_LOCAL, SOCK_STREAM, 0);

	struct sockaddr_un cli_addr;
	cli_addr.sun_family=AF_LOCAL;
	strcpy(cli_addr.sun_path, "client.socket");
	bind(cfd, (struct sockaddr *)&cli_addr, sizeof(cli_addr));

	struct sockaddr_un ser_addr;
	ser_addr.sun_family=AF_LOCAL;
	strcpy(ser_addr.sun_path, "server.socket");

	connect(cfd, (struct sockaddr *)&ser_addr, sizeof(ser_addr));
	while (1)
	{
		char buf[256];
		fgets(buf, sizeof(buf), stdin);
		write(cfd, buf, strlen(buf));
		read(cfd, buf, sizeof(buf));
		cout<<buf<<endl;

	}
		close(cfd);
		return 0;	
}

猜你喜欢

转载自blog.csdn.net/qq_34489443/article/details/88417223