Linux Socket多进程通信【服务端】

Linux Socket多进程通信【服务端】

Socket通信流程:

在这里插入图片描述
服务端代码:

#include<stdio.h>
#include<iostream>
#include<sys/socket.h>
#include<arpa/inet.h>
#include<unistd.h>
#include <string>

using namespace std;

int main() {
	int s_fd, c_fd;
	int resume = 0;
	char buf[BUFSIZ];
	int content_legth = 0;
	pid_t tpid;
	struct sockaddr_in serv_addr, client_addr;
	socklen_t len = sizeof(client_addr);
	serv_addr.sin_family = AF_INET;
	serv_addr.sin_addr.s_addr = htonl(INADDR_ANY);
	serv_addr.sin_port = htons(8888);
	s_fd = socket(AF_INET, SOCK_STREAM, 0);
	
	if (s_fd == -1) {
		perror("socket create fail");
		return 0;
	}
	setsockopt(s_fd, SOL_SOCKET, SO_REUSEADDR, &resume, sizeof(resume));
	int n = bind(s_fd, (struct sockaddr*)&serv_addr, sizeof(serv_addr));
	if (n == -1) {
		perror("bind fail");
		return 0;
	}
	int l = listen(s_fd, 30);
	if (l == -1) {
		perror("listen fail");
		return 0;
	}
	while (true)
	{
		c_fd = accept(s_fd, (struct sockaddr *)&client_addr,&len);
		if (c_fd < 0) {
			perror("accept");
			close(s_fd);
			exit(-1);
		}
		cout << "IP:"<<inet_ntoa(client_addr.sin_addr) <<"建立连接," << "Port:" << htons(client_addr.sin_port) << endl;
		tpid = fork();
		if (tpid < 0) {
			perror("fork create fail");
			return 0;
		}
		else if (tpid==0)
		{
			close(s_fd);
			break;
		}else
		{
			close(c_fd);
		}
	}
	if (tpid == 0) {
		while (true)
		{
			content_legth = read(c_fd, buf, sizeof(buf));
			string content = buf;
			if (content_legth < 0) {
				perror("client close!");
				close(c_fd);
				return 0;
			}else{
				cout <<"recv:" << content << endl;
				content = "recv the information\n";
				write(c_fd, content.data(), content.length());
			}
		}
	}
	else
	{
		close(s_fd);
	}

	return 0;
}
  • 10
    点赞
  • 5
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

dream1909

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值