服务器—客户端模式实现简单的通信

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/weixin_38822069/article/details/79825654

清明无事,总结一下最近学的linux功课。

利用TCP/IP/来实现,不过目前只能实现一对一你一句我一句的聊天。

有两个.c文件,ser.c和cli.c

Redhat系统,需要的头文件如下:

#include<stdio.h>
#include<unistd.h>
#include<stdlib.h>
#include<string.h>
#include<sys/socket.h>
#include<netinet/in.h>
#include<arpa/inet.h>

服务器


int main()
{
	//1
	int sockSer = socket(AF_INET, SOCK_STREAM, 0);
	if(sockSer == -1)
	{
		perror("socket.");
		exit(1);
	}

	//2
	struct sockaddr_in addeSer;
	addrSer.sin_family = AF_INET;
	addrSer.sin_port = htons(6666);
	addrSer.sin_addr_.s_addr = INADDR_ANY;

	socklen_t addrlen = sizeof(struct sockaddr);
	int ret = bind(sockSer, (struct sockaddr*)&addrSer, addrlen);
	if(ret == -1)
	{
		perror("bind.");
		exit(1);
	}

	//3
	int backlog = 5;
	ret = listen(sockSer, backlog);
	if(ret == -1)
	{
		perror("listen.");
		exit(1);
	}

	//4
	int sockConn;
	struct sockaddr_in addrCli;
	sockConn = accept(sockSer, (struct sockaddr*)&addrCli, &addrlen);
	if(sockConn == -1)
	{
		printf("Server Accept Client Connnect Fail.\n");
	}
	else 
	{
		printf("Server Accept Client Connect Success.\n");
	}

	char sendbuf[256];
	char recvbuf{256};
	while(1)
	{
		printf("Ser:>");
		scanf("%s",sendbuf);
		send(sockConn, sendbuf, strlen(sendbuf)+1, 0);

		recv(sockConn, recvbuf, 256, 0);
		printf("Cli:>%s\n",recvbuf);
	}
	close(sockSer);

	return 0;
}

用户

int main()
{
	int sockCli = socket(AF_INET, SOCK_STREAM, 0);
	if(sockCli == -1)
	{
		perror("socket.");
		exit(1);
	}

	struct sockaddr_in addeSer;
	addrSer.sin_family = AF_INET;
	addrSer.sin_port = htons(6666);
	addrSer.sin_addr_.s_addr = inet_addr("127.0.0.1");
	socklen_t addrlen = sizeof(struct sockaddr);
	int ret = connect(sockCli, (struct sockaddr*)&addrSer, addrlen);
	if(ret == -1)
		printf("Client Connect Server Fail.\n");
	else
		printf("Client Connect Server Success.\n");

	char sendbuf[256];
	char recvbuf{256};
	while(1)
	{
		recv(sockCli, recvbuf, 256, 0);
		printf("Ser:>%s\n",recvbuf);

		printf("Cli:>");
		scanf("%s",sendbuf);
		send(sockCli, sendbuf, strlen(sendbuf)+1, 0);
	}
	close(sockCli);

	return 0;
}

另外利用管道、信号、共享内存、消息队列也可以实现进程间通讯,不过上述代码可以在不同的机器之间实现通讯。

效果如小下图





没有更多推荐了,返回首页