一、问题描写叙述
如今以C/S架构为例。client向server端发送要查找的数字,server端启动线程中的线程进行对应的查询。将查询结果显示出来。
二、实现方案
1. 整个project以client、server、lib组织。例如以下图所看到的:
2. 进入lib。
socket.h、socket.c
/** @file socket.h @brief Socket API header file TCP socket utility functions, it provides simple functions that helps to build TCP client/server. @author wangzhicheng */ #ifndef SOCKET_H #define SOCKET_H #include <stdio.h> #include <stdlib.h> #include <string.h> #include <errno.h> #include <sys/socket.h> #include <sys/types.h> #include <resolv.h> #include <fcntl.h> #define MAX_CONNECTION 20 int TCPServerInit(int port, int *serverfd); int TCPServerWaitConnection(int serverfd, int *clientfd, char *clientaddr); int TCPServerSelect(int* serverfdlist, int num, int *clientfd, char *clientaddr); int TCPClientInit(int *clientfd); int TCPClientConnect(const int clientfd, const char *addr, int port); int TCPNonBlockRead(int clientfd, char* buf, int size); int TCPBlockRead(int clientfd, char* buf, int size); int TCPWrite(int clientfd, char* buf, int size); void TCPClientClose(int sockfd); void TCPServerClose(int sockfd); #endif
socket.c
#include "socket.h" /* * @brief initialize TCP server * @port port number for socket * @serverfd server socket fd * return server socked fd for success, on error return error code * */ int TCPServerInit(int port, int *serverfd) { struct sockaddr_in dest; // create socket , same as client *serverfd = socket(PF_INET, SOCK_STREAM, IPPROTO_TCP); if(*serverfd < 0) return -1; /// initialize structure dest memset((void*)&dest, '