TCP并发服务器/客户端模型
服务器TCP模型
#include "..." #include "..." #include "..." #define SERVER_PORT #define MAX_LISTEN int TCPServerModel (unsigned short publicPort) { int sockListen; int sockAccept; sockaddr_in serverAddr; sockaddr_in clientAddr; pid_t childPid; int addrLen = sizeof(sockaddr_in); // XXX 初始化监听套接口 sockListen = socket (AF_INET, SOCK_STREAM, 0); // XXX 初始化sockaddr_in memset (&serverAddr, 0, addrLen); serverAddr.sin_family = AF_INET; serverAddr.sin_port = htons(publicPort); serverAddr.sin_addr.s_addr = htons(INADDR_ANY); // XXX 绑定 - bind() bind(sockListen, (sockaddr *)&serverAddr, addrLen); // XXX 监听 - listen() listen (sockListen, MAX_LISTEN); while(true) { // XXX 接收连接 - accept() sockAccept = accept(sockListen, (sockaddr *)&clientAddr, &addrLen); if (!(childPid = fork())) { close(sockListen); // XXX 处理客户端数据 exit(0); } close(sockAccept); } return 0; }
客户端TCP模型
#include "..." #include "..." #include "..." #define SERVER_IP #define SERVER_PORT #define MAX_LISTEN int TCPClientModel (unsigned long serverIP) { int sockFd; sockaddr_in serverAddr; int addrLen = sizeof(serverAddr); // XXX 初始化套接口 sockFd = socket (AF_INET, SOCK_STREAM, 0); // XXX 初始化sockaddr_in memset (&serverAddr, 0, addrLen); serverAddr.sin_family = AF_INET; serverAddr.sin_port = htons(SERVER_PORT); serverAddr.sin_addr.s_addr = htonl(serverIP); // XXX 连接 - connect() connect (sockFd, (sockaddr *)&serverAddr, addrLen); // XXX 处理服务器数据 - 可根据实际情况具体实现 exit (0); }
除非注明,戊辰人博客文章均为原创,转载请以链接形式标明本文地址