函数原型: int listen(int sockfd, int backlog); 作用: It puts the server socket in a passive mode, where it waits for the client to approach the server to make a connection. 参数: (1) sockfd 需要监听套接字对应的文件描述符 (2) backlog 全连接队列的最大长度。如果有多个客户端同时发来连接请求,此时未被服务器处理的连接就会放入连接队列(超出的连接请求会被忽略),该参数代表的就是这个全连接队列的最大长度,一般不要设置太大,设置为5或10即可 返回值: 成功: 返回0 失败: 返回-1,设置errno
2.accept()
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15
函数原型: int accept(int sockfd, struct sockaddr *addr, socklen_t *addrlen); 作用: It extracts the first connection request on the queue of pending connections for the listening socket, sockfd, creates a new connected socket, and returns a new file descriptor referring to that socket. At this point, the connection is established between client and server, and they are ready to transfer data. 参数: (1) sockfd 需要监听套接字对应的文件描述符(监听套接字) (2) addr 对端网络相关属性信息,包括协议家族、ip和端口等 (3) addrlen addr结构体长度,返回实际读取到的addr结构体长度(输入输出型参数) 返回值: 成功: 返回一个新的socket文件描述符(服务套接字),用于和客户端通信 失败: 返回-1,设置errno 1.监听套接字:用于获取客户端发来的连接请求。accept函数会不断从监听套接字当中获取新连接。 2.accept函数返回的套接字:用于为本次accept获取到的连接提供服务。监听套接字的任务只是不断获取新连接,而真正为这些连接提供服务的套接字是accept函数返回的套接字
3.connect()
1 2 3 4 5 6 7 8 9 10 11 12 13
函数原型: int connect(int sockfd, const struct sockaddr *addr, socklen_t addrlen); 作用: The connect() system call connects the socket referred to by the file descriptor sockfd to the address specified by addr. Server's address and port is specified in addr. 参数: (1) sockfd 需要连接套接字对应的文件描述符(通过该套接字发起连接请求) (2) addr 对端网络相关属性信息,包括协议家族、ip和端口等 (3) addrlen addr结构体长度 返回值: 成功: 连接成功 失败: 返回-1,设置errno
#include <sys/socket.h> 函数原型: int setsockopt(int sockfd, int level, int optname, const void *optval, socklen_t optlen); 作用: This helps in manipulating options for the socket referred by the file descriptor sockfd. This is completely optional, but it helps in reuse of address and port. Prevents error such as: "address already in use" 参数: (1) sockfd 套接字描述符 (2) level 设置选项的级别,如果想要在套接字级别上设置选项,就必须把level设置为 SOL_SOCKET (3) optname 需要设置的选项 (4) optval 指向存放选项值的缓冲区 (5) optlen optval 缓冲区的长度 返回值: 成功: 返回0 失败: 返回-1, 设置errno