datetime:2023/03/21 15:52
author:nzb
多线程并发的网络服务端框架
服务端
#include "../_freecplus.h"
void *pthmain(void *arg);
CTcpServer TcpServer;
vector<long> vpthid;
void mainexit(int sig);
void pthmainexit(void *arg);
CLogFile logfile;
int main(int argc, char *argv[]) {
signal(2, mainexit);
signal(15, mainexit);
logfile.Open("/tmp/demo48.log", "a+");
if (TcpServer.InitServer(5858) == false)
{
logfile.Write("TcpServer.InitServer(5858) failed.\n");
return -1;
}
while (true) {
if (TcpServer.Accept() == false)
{
logfile.Write("TcpServer.Accept() failed.\n");
return -1;
}
logfile.Write("客户端(%s)已连接。\n", TcpServer.GetIP());
pthread_t pthid;
if (pthread_create(&pthid, NULL, pthmain, (void *) (long) TcpServer.m_connfd) != 0) {
logfile.Write("pthread_create failed.\n");
return -1;
}
vpthid.push_back(pthid);
}
return 0;
}
void *pthmain(void *arg) {
pthread_cleanup_push(pthmainexit, arg);
pthread_detach(pthread_self());
pthread_setcanceltype(PTHREAD_CANCEL_DISABLE, NULL);
int sockfd = (int) (long) arg;
int ibuflen = 0;
char strbuffer[1024];
while (true) {
memset(strbuffer, 0, sizeof(strbuffer));
if (TcpRead(sockfd, strbuffer, &ibuflen, 300) == false) break;
logfile.Write("接收:%s\n", strbuffer);
strcat(strbuffer, "ok");
logfile.Write("发送:%s\n", strbuffer);
if (TcpWrite(sockfd, strbuffer) == false) break;
}
logfile.Write("客户端已断开。\n");
pthread_cleanup_pop(1);
pthread_exit(0);
}
void mainexit(int sig) {
logfile.Write("mainexit begin.\n");
TcpServer.CloseListen();
for (int ii = 0; ii < vpthid.size(); ii++) {
logfile.Write("cancel %ld\n", vpthid[ii]);
pthread_cancel(vpthid[ii]);
}
logfile.Write("mainexit end.\n");
exit(0);
}
void pthmainexit(void *arg) {
logfile.Write("pthmainexit begin.\n");
close((int) (long) arg);
for (int ii = 0; ii < vpthid.size(); ii++) {
if (vpthid[ii] == pthread_self()) {
vpthid.erase(vpthid.begin() + ii);
}
}
logfile.Write("pthmainexit end.\n");
}
客户端
#include "../_freecplus.h"
int main(int argc, char *argv[]) {
printf("pid=%d\n", getpid());
CTcpClient TcpClient;
if (TcpClient.ConnectToServer("172.21.0.3", 5858) == false)
{
printf("TcpClient.ConnectToServer(\"172.21.0.3\",5858) failed.\n");
return -1;
}
char strbuffer[1024];
for (int ii = 0; ii < 50; ii++)
{
memset(strbuffer, 0, sizeof(strbuffer));
snprintf(strbuffer, 50, "(%d)这是第%d个超级女生,编号%03d。", getpid(), ii + 1, ii + 1);
printf("发送:%s\n", strbuffer);
if (TcpClient.Write(strbuffer) == false) break;
memset(strbuffer, 0, sizeof(strbuffer));
if (TcpClient.Read(strbuffer, 20) == false) break;
printf("接收:%s\n", strbuffer);
sleep(1);
}
}