Linux:socket实现两个进程之间的通信

时间:2024-10-26 15:30:03

本文展示了服务端和客户端进行网络通信的示例:服务端向客户端发送数据,客户端读取服务端发送过来的数据;废话不多说,直接上代码!
服务端代码:

#include <sys/socket.h>
#include <cstdlib>
#include <unistd.h>
#include <cstdio>
#include <sys/types.h>
#include <arpa/inet.h>
int main()
{

	//Step01:Create a socket
	int fd_monitor = socket(AF_INET,SOCK_STREAM,0);
	if(fd_monitor==-1)
	{
		printf("Failed to create file descriptor!\n");
		return -1;
	}

	//Step02;Set ip address and port for current processing
	sockaddr_in myaddr;
	myaddr.sin_family = AF_INET;
	myaddr.sin_addr.s_addr = INADDR_ANY;
	myaddr.sin_port = htons(8888);


	int iResBind = bind(fd_monitor,(sockaddr*)&myaddr,sizeof(myaddr));
	if(iResBind==-1){
		printf("Failed to bind!\n");
		return -2;
	}

	//Step03:Listen connection
	int iResListen = listen(fd_monitor,128);
	if(iResListen==-1){
		printf("Failed to listen!\n");
		return -3;
	}

	//Step04:Wait connection from client
	int fd_communication = accept(fd_monitor,NULL,NULL);
	if(fd_communication < 0)
	{
		printf("Failed to accept!\n");
		return -4;
	}

	//Step05:Write data to client
	char buffer[1024];
	while(1)
	{
		sprintf(buffer,"Hello! I am server!\n");
		write(fd_communication,buffer,sizeof(buffer));
		sleep(3);
	}

	//Step06:Close communication file descriptor
	close(fd_communication);
	return 0;

}

客户端代码:

#include <cstdlib>
#include <unistd.h>
#include <sys/socket.h>
#include <arpa/inet.h>
#include <cstdio>
#include <cstring>
#define SERVER_IP "127.0.0.1"
#define SERVER_PORT 8888

int main()
{
	//Step01:Create socket
	int fd_communication = socket(AF_INET,SOCK_STREAM,0);
	if(fd_communication==-1)
	{
		printf("Failed to create socket!\n");
		return -1;
	}

	//Step02:Connect server
	sockaddr_in addr;
	addr.sin_family = AF_INET;
	addr.sin_port =htons(SERVER_PORT);
	inet_pton(AF_LOCAL,SERVER_IP,&addr.sin_addr.s_addr);
	int iResConnect = connect(fd_communication,(sockaddr*)&addr,sizeof(addr));
	if(iResConnect==-1)
	{
		printf("Failed to connect server\n");
		return -2;
	}

	//Step03:Communicate with server
	char buffer[1024];
	while(1){
		memset(buffer,0,sizeof(buffer));
		int iLen = read(fd_communication,buffer,sizeof(buffer));
		printf("recv data:%s\n",buffer);
		sleep(1);
	}
	close(fd_communication);
	return 0;
}

需要说明的是:服务端创立的套接字对象需要绑定ip地址和端口号;客户端connect服务端的时候需要提供服务端的ip地址和端口号(服务端提供服务的进程的端口号)