1、服务器端
#include <sys/types.h> #include <sys/socket.h>int listen(int sockfd, int backlog);返回:成功返回0,出错返回-1。参数:sockfd:套接字的文件描述符backlog:定义了sockfd的挂起连接队列可能增长的最大长度。int accept(int sockfd, struct sockaddr *addr, socklen_t *addrlen);参数:sockfd:套接字的文件描述符。addr:指向sockaddr结构的指针。这个结构是用通信层已知的对等套接字的地址填充的。addrlen:结果参数,返回时,它将包含对等地址的实际大小。
示例:
2、客户端
#include <sys/socket.h>int connect(int sockfd, const struct sockaddr *addr,socklen_t addrlen);返回:成功返回0,出错返回-1。功能:系统调用将文件描述符sockfd引用的套接字连接到addr指定的地址。参数:addrlen:指定addr的大小。addr:要连接的服务器地址,其中地址的格式由套接字sockfd的地址空间决定
示例:
3、服务器完整示例
nt main(void)
{//1. 创建套接字int serverfd = socket(AF_INET, SOCK_STREAM, 0);if(serverfd < 0){perror("创建套接字失败");exit(1);}//2. 绑定套接字struct sockaddr_in addr;memset(&addr, 0, sizeof(addr));addr.sin_family = AF_INET;addr.sin_port = htons(PORT);addr.sin_addr.s_addr = INADDR_ANY;if(bind(serverfd, (struct sockadr*)&addr, sizeof(addr)) < 0){perror("绑定套接字失败");exit(1);}//3. 监听if(listen(serverfd, 5) < 0){perror("监听套接字失败");exit(1);}struct sockaddr_int client_addr;socklen_t client_len = sizeof(client_addr);fd_set fds, tds;FD_ZERO(&fds);FD_SET(serverfd, &fds);//4. 接受while(1){tds = fds;//使用select同时监听serverfd与其他若干clientfd,int ret = select(FD_SETSIZE, &tds, NULL, NULL, NULL);if(ret < 0){perror("");exit(1);}else if(ret > 0){//准备好了int i = 0, j = 0;for(i = 3; i < FD_SETSIZE && j < ret; i++){if(FD_ISSET(i, &tds)){//有东西可读j++;if(i == serverfd){//需要acceptint clientfd = 0;if((clientfd = accept(serverfd, (struct sockaddr*)&client_addr, &client_len)) < 0){perror("");exit(1);}else{//接受成功printf("新的连接:ip:%s port:%d\n", inet_ntop(client_addr.sin_addr.s_addr), ntohs(client_addr.sin_port));FD_SET(clientfd, &fds);}}else{char str[1024] = "";//客户端读取if(read(i, str, sizeof(str)) == 0){//套接字关闭FD_CLR(i, &fds);close(i);}else{//switch(){}}}}}}else{}}return 0;
}
4、客户端完整示例
int main(void)
{//1. 创建套接字client_sockfd = socket(AF_INET, SOCK_STREAM, 0);if(client_sockfd < 0){perror("");exit(1);}//2. 连接struct sockaddr_in addr;memset(&addr, 0, sizeof(addr));addr.sin_family = AF_INET;inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);addr.sin_port = htons(12000);if(connect(client_sockfd, (struct sockaddr*)&addr, sizeof(addr)) < 0){perror("");exit(1);}pthread_t pid;pthread_attr_t attr; pthread_attr_init(&attr);pthread_attr_setdetachstate(&attr, PTHREAD_CREATE_DETACHED);pthread_create(&pid, &attr, pthread_recv, &client_sockfd);main_menu();// 循环close(client_sockfd);return 0;
}