TCP并发server模型(三)

时间:2024-08-21 17:33:20

本篇博客讲述的是单client单线程模型,该模型相同由主进程统一accept,仅仅是将fork改为了pthread_create。

与进程相比,线程有非常多长处(速度快,占用资源少。数据能够共享)。

该模型结构如图所看到的:

TCP并发server模型(三)

与上一篇博客讲述的模型非常相似,源码同上一篇相比仅仅有少量更改而已,亦不解说。

服务器端代码例如以下:

/*
author:arvik
purpose:test the server simultaneity
email:1216601195@qq.com
****: http://blog.****.net/u012819339
*/ #include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <time.h>
#include <string.h>
#include <unistd.h>
#include <stdio.h>
#include <arpa/inet.h>
#include <pthread.h> #define BUFFLEN 1024
#define SERVER_PORT 8887
#define BACKLOG 3 static void handle_request(void *argv)
{
int s_c = *((int *)argv);
char buff[BUFFLEN];
int n = 0; memset(buff, 0, sizeof(buff));
n = recv(s_c, buff, BUFFLEN, 0); if(n>0)
{
printf("receive msg from client: %s\n", buff);
} close(s_c);
} static int handle_connect(int s_s)
{
int s_c;
struct sockaddr_in from;
socklen_t len = sizeof(from);
pthread_t thread_do; while(1)
{
s_c = accept(s_s, (struct sockaddr*)&from, &len); //block
if(s_c>0)
{
pthread_create(&thread_do, NULL, (void*)handle_request, &s_c);
}
}
} int main()
{
int s_s;
struct sockaddr_in local; s_s = socket(AF_INET, SOCK_STREAM, 0); memset(&local, 0, sizeof(local));
local.sin_family = AF_INET;
local.sin_addr.s_addr = inet_addr("127.0.0.1");//htonl(INADDR_ANY);
local.sin_port = htons(SERVER_PORT); if(bind(s_s, (struct sockaddr*)&local, sizeof(local)))
{
printf("bind socket failed!\n");
return -1;
} listen(s_s, BACKLOG); handle_connect(s_s); close(s_s); return 0;
}

client代码不变。

见上一篇博客!

相关文章