网络编程:单客户端单线程统一accpet TCP并发服务器(简单时间服务器)
写在前面的话
由主进程统一的处理客户端连接,当客户端连接到来时才创建子线程来处理客户端请求。参考教材:Linux网络编程。
题目(功能)
- 服务端:接收客户端时间请求,返回本地时间
- 客户端:发送时间请求,接收客户端返回的时间并打印
服务端代码
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <time.h>
#include <string.h>
#include <stdio.h>
#include <unistd.h>
#include <pthread.h>
#define BUFFLEN 1024
#define PORT 45678
#define BACKLOG 5
//处理客户端请求
static void handle_request(void *argv)
{
int s_c = *((int *)argv);
char buff[BUFFLEN];
while (1)
{
memset(buff, 0, BUFFLEN); /*清零*/
int n = recv(s_c, buff, BUFFLEN, 0); /*接收发送方数据*/
if (n > 0 && !strncmp(buff, "TIME", 4)) /*判断是否合法接收数据*/
{
memset(buff, 0, BUFFLEN); /*清零*/
time_t now = time(NULL); /*当前时间*/
sprintf(buff, "%24s\r\n", ctime(&now)); /*将时间复制入缓冲区*/
send(s_c, buff, strlen(buff), 0); /*发送数据*/
}
close(s_c);
}
}
//处理客户端连接
static int handle_connect(int s_s)
{
pthread_t thread_do;
struct sockaddr_in from;
socklen_t len = sizeof(from);
//接收客户端连接
int s_c = accept(s_s, (struct sockaddr *)&from, &len);
//连接成功
if (s_c > 0)
{
pthread_create(&thread_do, NULL, (void *)handle_request, &s_c);
}
}
int main(int argc, char *argv[])
{
struct sockaddr_in local;
/*建立TCP套接字*/
int s_s = socket(AF_INET, SOCK_STREAM, 0);
/*初始化地址*/
memset(&local, 0, sizeof(local)); /*清零*/
local.sin_family = AF_INET; /*AF_INET协议族*/
local.sin_addr.s_addr = htonl(INADDR_ANY); /*任意本地地址*/
local.sin_port = htons(PORT); /*服务器端口*/
/*将套接字文件描述符绑定到本地地址和端口*/
bind(s_s, (struct sockaddr *)&local, sizeof(local));
listen(s_s, BACKLOG); /*侦听*/
//处理客户端
handle_connect(s_s);
close(s_s);
return 0;
}
客户端代码
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <string.h>
#include <unistd.h>
#include <stdio.h>
#define BUFFLEN 1024
#define SERVER_PORT 45677
int main(int argc, char *argv[])
{
int s; /*服务器套接字文件描述符*/
struct sockaddr_in server; /*本地地址*/
char buff[BUFFLEN]; /*收发数据缓冲区*/
int n = 0; /*接收字符串长度*/
/*建立TCP套接字*/
s = socket(AF_INET, SOCK_STREAM, 0);
/*初始化地址*/
memset(&server, 0, sizeof(server)); /*清零*/
server.sin_family = AF_INET; /*AF_INET协议族*/
server.sin_addr.s_addr = htonl(INADDR_ANY); /*任意本地地址*/
server.sin_port = htons(SERVER_PORT); /*服务器端口*/
/*连接服务器*/
connect(s, (struct sockaddr *)&server, sizeof(server));
memset(buff, 0, BUFFLEN); /*清零*/
strcpy(buff, "TIME"); /*复制发送字符串*/
/*发送数据*/
send(s, buff, strlen(buff), 0);
memset(buff, 0, BUFFLEN); /*清零*/
/*接收数据*/
n = recv(s, buff, BUFFLEN, 0);
/*打印消息*/
if (n > 0)
{
printf("TIME:%s", buff);
}
close(s);
return 0;
}