Linux进程间通信IPC(六)--- socket

套接字

套接字实现进程间通信可用于网络编程,两个进程通过socket套接字进行收发数据的通信。

下面实现一个简单的局域网群聊天室实例:

#include <iostream>
#include <cstring>
#include <time.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
using namespace std;

int main(int argc,char* argv[])
{
	int sfd=socket(AF_INET,SOCK_DGRAM,0);

	
	int opt_val=1;
	setsockopt(sfd,SOL_SOCKET,SO_BROADCAST,&opt_val,sizeof(opt_val));


	sockaddr_in addrSrv;
	addrSrv.sin_family=AF_INET;
	addrSrv.sin_addr.s_addr=htonl(INADDR_ANY);
	addrSrv.sin_port=htons(1234);

	bind(sfd,(sockaddr*)&addrSrv,sizeof(addrSrv));

	
	sockaddr_in addrClient;
	addrClient.sin_family=AF_INET;
	inet_aton("255.255.255.255",&addrClient.sin_addr);
	addrClient.sin_port=htons(1234);

	char buff[1024];

	int cid=fork();

	if(cid>0)//父进程发送数据
	{
		while(1)
		{
			cin>>buff;
			int ret=sendto(sfd,buff,strlen(buff),0,(sockaddr*)&addrClient,sizeof(addrClient));		

			if(ret<=0)
			{
				cout<<"send error!"<<endl;
			}
		}
	}
	else if(cid==0)//子进程接收数据
	{
		sockaddr_in addrFrom;
		socklen_t  addr_len;
		tm *t=NULL;
		time_t ts;

		while(1)
		{
			addr_len=sizeof(addrFrom);
			memset(buff,0,sizeof(buff));
			recvfrom(sfd,buff,sizeof(buff)-1,0,(sockaddr*)&addrFrom,&addr_len);

		/*	if(addrSrv.sin_addr.s_addr==addrFrom.sin_addr.s_addr)
			{
				continue;
			}
		*/

			time(&ts);			
			t=localtime(&ts);//获取系统当前时间
			cout<<inet_ntoa(addrFrom.sin_addr)<<" ("<<t->tm_hour<<":"<<t->tm_min<<") "<<"说:"<<buff<<endl;
		}
	}

	
	close(sfd);	
	

	return 0;
}

运行结果:

Linux进程间通信IPC(六)--- socket_第1张图片

你可能感兴趣的:(编程,linux,socket,网络,聊天)