当前位置:网站首页>4-20-4-23 concurrent server, TCP state transition;
4-20-4-23 concurrent server, TCP state transition;
2022-07-03 14:49:00 【III VII】
To achieve TCP The communication server handles concurrent tasks , Use multithreading or multiprocessing to solve .
Ideas :
- A parent process , Multiple subprocesses
2. The parent process is responsible for waiting and accepting the client's connection
3. Subprocesses : Complete communication , Accept a client connection , A child process is created for communication .
Server code :
#include <stdio.h>
#include <arpa/inet.h>
#include <unistd.h>
#include <stdlib.h>
#include <string.h>
#include <signal.h>
#include <wait.h>
#include <errno.h>
void recyleChild(int arg) {
while(1) {
int ret = waitpid(-1, NULL, WNOHANG);
if(ret == -1) {
// All child processes are recycled
break;
}else if(ret == 0) {
// There are sub processes alive
break;
} else if(ret > 0){
// It's recycled
printf(" Subprocesses %d It's recycled \n", ret);
}
}
}
int main() {
struct sigaction act;
act.sa_flags = 0;
sigemptyset(&act.sa_mask);
act.sa_handler = recyleChild;
// Register signal capture
sigaction(SIGCHLD, &act, NULL);
// establish socket
int lfd = socket(PF_INET, SOCK_STREAM, 0);
if(lfd == -1){
perror("socket");
exit(-1);
}
struct sockaddr_in saddr;
saddr.sin_family = AF_INET;
saddr.sin_port = htons(9999);
saddr.sin_addr.s_addr = INADDR_ANY;
// binding
int ret = bind(lfd,(struct sockaddr *)&saddr, sizeof(saddr));
if(ret == -1) {
perror("bind");
exit(-1);
}
// monitor
ret = listen(lfd, 128);
if(ret == -1) {
perror("listen");
exit(-1);
}
// Keep waiting for the client to connect
while(1) {
struct sockaddr_in cliaddr;
int len = sizeof(cliaddr);
// Accept the connection
int cfd = accept(lfd, (struct sockaddr*)&cliaddr, &len);
if(cfd == -1) {
if(errno == EINTR) {
continue;
}
perror("accept");
exit(-1);
}
// Every connection comes in , Create a child process to communicate with the client
pid_t pid = fork();
if(pid == 0) {
// Subprocesses
// Get client information
char cliIp[16];
inet_ntop(AF_INET, &cliaddr.sin_addr.s_addr, cliIp, sizeof(cliIp));
unsigned short cliPort = ntohs(cliaddr.sin_port);
printf("client ip is : %s, prot is %d\n", cliIp, cliPort);
// Receive data from client
char recvBuf[1024];
while(1) {
int len = read(cfd, &recvBuf, sizeof(recvBuf));
if(len == -1) {
perror("read");
exit(-1);
}else if(len > 0) {
printf("recv client : %s\n", recvBuf);
} else if(len == 0) {
printf("client closed....\n");
break;
}
write(cfd, recvBuf, strlen(recvBuf) + 1);
}
close(cfd);
exit(0); // Exit the current subprocess
}
}
close(lfd);
return 0;
}
Client code :
// TCP Communication client
#include <stdio.h>
#include <arpa/inet.h>
#include <unistd.h>
#include <string.h>
#include <stdlib.h>
int main() {
// 1. Create socket
int fd = socket(AF_INET, SOCK_STREAM, 0);
if(fd == -1) {
perror("socket");
exit(-1);
}
// 2. Connect to the server side
struct sockaddr_in serveraddr;
serveraddr.sin_family = AF_INET;
inet_pton(AF_INET, "192.168.87.128", &serveraddr.sin_addr.s_addr);
serveraddr.sin_port = htons(9999);
int ret = connect(fd, (struct sockaddr *)&serveraddr, sizeof(serveraddr));
if(ret == -1) {
perror("connect");
exit(-1);
}
// 3. signal communication
char recvBuf[1024];
int i = 0;
while(1) {
sprintf(recvBuf, "data : %d\n", i++);
// Send data to the server
write(fd, recvBuf, strlen(recvBuf)+1);
int len = read(fd, recvBuf, sizeof(recvBuf));
if(len == -1) {
perror("read");
exit(-1);
} else if(len > 0) {
printf("recv server : %s\n", recvBuf);
} else if(len == 0) {
// Indicates that the server is disconnected
printf("server closed...");
break;
}
sleep(1);
}
// Close the connection
close(fd);
return 0;
}
Run a screenshot :

Multithreaded concurrent server
#include <stdio.h>
#include <arpa/inet.h>
#include <unistd.h>
#include <stdlib.h>
#include <string.h>
#include <pthread.h>
struct sockInfo {
int fd; // File descriptor for communication
struct sockaddr_in addr;
pthread_t tid; // Thread number
};
struct sockInfo sockinfos[128];
void * working(void * arg) {
// The sub thread communicates with the client cfd Client information Thread number
// Get client information
struct sockInfo * pinfo = (struct sockInfo *)arg;
char cliIp[16];
inet_ntop(AF_INET, &pinfo->addr.sin_addr.s_addr, cliIp, sizeof(cliIp));
unsigned short cliPort = ntohs(pinfo->addr.sin_port);
printf("client ip is : %s, prot is %d\n", cliIp, cliPort);
// Receive data from client
char recvBuf[1024];
while(1) {
int len = read(pinfo->fd, &recvBuf, sizeof(recvBuf));
if(len == -1) {
perror("read");
exit(-1);
}else if(len > 0) {
printf("recv client : %s\n", recvBuf);
} else if(len == 0) {
printf("client closed....\n");
break;
}
write(pinfo->fd, recvBuf, strlen(recvBuf) + 1);
}
close(pinfo->fd);
return NULL;
}
int main() {
// establish socket
int lfd = socket(PF_INET, SOCK_STREAM, 0);
if(lfd == -1){
perror("socket");
exit(-1);
}
struct sockaddr_in saddr;
saddr.sin_family = AF_INET;
saddr.sin_port = htons(9999);
saddr.sin_addr.s_addr = INADDR_ANY;
// binding
int ret = bind(lfd,(struct sockaddr *)&saddr, sizeof(saddr));
if(ret == -1) {
perror("bind");
exit(-1);
}
// monitor
ret = listen(lfd, 128);
if(ret == -1) {
perror("listen");
exit(-1);
}
// Initialization data
int max = sizeof(sockinfos) / sizeof(sockinfos[0]);
for(int i = 0; i < max; i++) {
bzero(&sockinfos[i], sizeof(sockinfos[i]));
sockinfos[i].fd = -1;
sockinfos[i].tid = -1;
}
// Loop waiting for client connection , Once a client connects in , Just create a child thread to communicate
while(1) {
struct sockaddr_in cliaddr;
int len = sizeof(cliaddr);
// Accept the connection
int cfd = accept(lfd, (struct sockaddr*)&cliaddr, &len);
struct sockInfo * pinfo;
for(int i = 0; i < max; i++) {
// Find a usable... From this array sockInfo Elements
if(sockinfos[i].fd == -1) {
pinfo = &sockinfos[i];
break;
}
if(i == max - 1) {
sleep(1);
i--;
}
}
pinfo->fd = cfd;
memcpy(&pinfo->addr, &cliaddr, len);// take cliaddr copy to addr;
// Create child threads
pthread_create(&pinfo->tid, NULL, working, pinfo);
pthread_detach(pinfo->tid);// Thread recycling is not blocked ;
}
close(lfd);
return 0;
}
4.23TCP State transition

Three handshakes : Both sides established State to establish a connection 

边栏推荐
- 7-9 one way in, two ways out (25 points)
- Implement Gobang with C language
- puzzle(016.4)多米诺效应
- 556. 下一个更大元素 III : 简单构造模拟题
- Zzuli:1044 failure rate
- Zzuli:1040 sum of sequence 1
- Zzuli:1048 factorial table
- Address book sorting
- Analysis of gene family characteristics - chromosome location analysis
- Code writing and playing method of tonybot humanoid robot at fixed distance
猜你喜欢
随机推荐
CentOS7部署哨兵Redis(带架构图,清晰易懂)
零拷贝底层剖析
Protobuf and grpc
Mongodb index
Zzuli:1054 monkeys eat peaches
Solve the problem that PR cannot be installed on win10 system. Pr2021 version -premiere Pro 2021 official Chinese version installation tutorial
Tailing rushes to the scientific and Technological Innovation Board: it plans to raise 1.3 billion, and Xiaomi Changjiang is the shareholder
Zzuli:1043 max
Zzuli:1044 failure rate
tonybot 人形機器人 紅外遙控玩法 0630
Luogu p5536 [xr-3] core city solution
Zzuli:1058 solving inequalities
洛谷P3065 [USACO12DEC]First! G 题解
PS tips - draw green earth with a brush
cpu飙升排查方法
Zzuli:1059 highest score
Zzuli: cumulative sum of 1050 factorials
亚马逊、速卖通、Lazada、Shopee、eBay、wish、沃尔玛、阿里国际、美客多等跨境电商平台,测评自养号该如何利用产品上新期抓住流量?
Code writing and playing method of tonybot humanoid robot at fixed distance
Awvs batch operation script






![洛谷P4047 [JSOI2010]部落划分 题解](/img/7f/3fab3e94abef3da1f5652db35361df.png)
