1. The client calls sequence
Client programming sequence is as follows:
-
Call the socket function to create a socket
-
Call connect server connections
-
Call the I / O functions (read / write) and server-side communications
-
Calling close socket is closed
2. The server-side call sequence
Server programming sequence is as follows:
-
Call the socket function to create a socket
-
Call bind bind local address and port
-
Start calling listen listening
-
A call to accept client connections extracted from the connected queue
-
Call the I / O functions (read / write) to communicate with clients
-
Call the close function closes the socket
3. Common Functions
3.1. Socket and address binding function
(1) bind address
#include <sys/socket.h>
int bind(int sockfd, const struct sockaddr *addr, socklen_t len);
Returns: the successful return 0, -1 error
Special bind address Introduction
A host can have multiple network interfaces and multiple IP addresses, if we only care about the connection request for an address, we can specify a specific local IP address, if you want to respond to connection requests on all interfaces necessary to use a special address INADDR_ANY
#define INADDR_ANY (uint32_t)0x00000000
Listen for connection requests on the server for all IP obtained
struct sockaddr_in servaddr;
memset(&servaddr, 0, sizeof(servaddr));
servaddr.sin_addr.s_addr = INADDR_ANY;
3.2. Find an address bound to the socket
#include <sys/socket.h>
int getsockname(int sockfd, struct sockaddr *restrict_addr, socklen_t *restrict_alenp);
Returns: the successful return 0, -1 error
3.3. Getting the other address
int getpeername(int sockfd, struct sockaddr *restrict_addr, socklen_t *restrict_alenp);
Returns: the successful return 0, -1 error
3.4. To establish a connection on the server side
#include <sys/socket.h>
int listen(int sockfd, int backlog);
返回:成功返回0,出错返回-1。
backlog指定进行客户端连接排队的队列长度。
int accept(int sockfd, struct sockaddr *restrict_addr, socklen_t *restrict_len);
返回:成功返回一个新的sockfd(客户端的)。
3.5.客户端请求连接
#include <sys/socket.h>
int connect(int sockfd, const struct sockaddr *addr, socklen_t len);
返回:成功返回0,出错返回-1
3.6.IO操作函数
read和write函数默认都是阻塞性的读写函数。此时需要考虑服务器的并发处理。
4.服务器端并发性处理
4.1.多进程模型
弊端:进程占用系统资源,当子进程过多将占用过多的系统资源,难以处理大并发的场景。
4.2.多线程模型
以分离状态去启动子线程,子线程运行完后自动释放空间。