【Linux】TCP协议实现CS模式

【Linux】TCP协议实现CS模式,第1张

【Linux】TCP协议实现C/S模式 (一)简单C/S模型

(1)服务器端
  • 代码:
#include 
#include 
#include 
#include 
#include 
#include 
#include 
#include 
void Server()
{
	int sockfd = socket(AF_INET, SOCK_STREAM, 0);
	if(sockfd == -1)
	{
		perror("socket create err");
		return;
	}

	struct sockaddr_in saddr, caddr;
	int len_ser = sizeof(saddr);
	int len_cli = sizeof(caddr);

	memset(&saddr, 0, len_ser);
	memset(&caddr, 0, len_cli);

	saddr.sin_family = AF_INET;
	saddr.sin_port = htons(8000);
	saddr.sin_addr.s_addr = inet_addr("127.0.0.1");
	int ret = bind(sockfd, (struct sockaddr*)&saddr, len_ser);
	if(ret == -1)
	{
		perror("bind err");
		return;
	}

	ret = listen(sockfd, 5);
	if(ret == -1)
	{
		perror("listen err");
		return;
	}


	while(1)
	{
		printf("server have started, wait linking...n");
		int cli_sockfd = accept(sockfd, (struct sockaddr*)&caddr, &len_cli);
		
		while(1)
		{
			char buff[128] = {0};
			ret = recv(cli_sockfd, buff, 127, 0);
			if(ret <= 0)
			{
				printf("one client closen");
				close(cli_sockfd);
				break;
			}

			printf("cli : %sn", buff);
			memset(buff, 0, 128);
			printf("input send to cli : ");
			fflush(stdout);
			fgets(buff, 127, stdin);
			int len = strlen(buff);
			buff[len - 1] = '';
			send(cli_sockfd, buff, len, 0);
		}
	}

	close(sockfd);
}

int main()
{
	Server();
	return 0;
}
(2)客户端
  • 代码:
#include 
#include 
#include 
#include 
#include 
#include 
#include 
#include 

void client()
{
	int sockfd = socket(AF_INET, SOCK_STREAM, 0);
	if(sockfd == -1)
	{
		perror("socket err");
		return;
	}

	struct sockaddr_in saddr;
	int len_ser = sizeof(saddr);
	memset(&saddr, 0, len_ser);

	saddr.sin_family = AF_INET;
	saddr.sin_port = htons(8000);
	saddr.sin_addr.s_addr = inet_addr("127.0.0.1");
	
	int ret = connect(sockfd, (struct sockaddr*)&saddr, len_ser);
	if(ret == -1)
	{
		perror("connect err");	
		return;
	}
	
	printf("connect sucessful...n");
	while(1)
	{
		printf("input to server data:");
		fflush(stdout);

		char buff[128] = {0};
		fgets(buff, 127, stdin);
		int len = strlen(buff);
		buff[len - 1] = '';
		if(strcmp(buff, "end") == 0)
		{
			break;
		}
			
		send(sockfd, buff, len, 0);
		memset(buff, 0, 128);
		ret = recv(sockfd, buff, 127, 0);
		if(ret <= 0)
		{
			perror("server unnormal close");
			break;
		}
		printf("ser:%sn", buff);
	}
	close(sockfd);
}

int main()
{
	client();
	return 0;
}
  • 交互结果:
  • 客户端连接服务器后使用netstat -natp查看下ip和端口的使用情况:

欢迎分享,转载请注明来源:内存溢出

原文地址: http://outofmemory.cn/zaji/5635473.html

(0)
打赏 微信扫一扫 微信扫一扫 支付宝扫一扫 支付宝扫一扫
上一篇 2022-12-16
下一篇 2022-12-16

发表评论

登录后才能评论

评论列表(0条)

保存