用到的所有方法所需要的参数可以在wrap.c文件中查询,wrap中找不到的直接通过man手册查询
1.首先介绍一下我自己写的包裹文件,里面有各种在可能要用到的方法
wrap.c:
#include <stdlib.h>
#include <stdio.h>
#include <unistd.h>
#include <errno.h>
#include <string.h>
#include <sys/socket.h>
#include <arpa/inet.h>
#include <strings.h>void perr_exit(const char *s)
{perror(s);exit(-1);
}int Accept(int fd, struct sockaddr *sa, socklen_t *salenptr)
{int n;again:if ((n = accept(fd, sa, salenptr)) < 0) {if ((errno == ECONNABORTED) || (errno == EINTR))//如果是被信号中断和软件层次中断,不能退出goto again;elseperr_exit("accept error");}return n;
}int Bind(int fd, const struct sockaddr *sa, socklen_t salen)
{int n;if ((n = bind(fd, sa, salen)) < 0)perr_exit("bind error");return n;
}int Connect(int fd, const struct sockaddr *sa, socklen_t salen)
{int n;if ((n = connect(fd, sa, salen)) < 0)perr_exit("connect error");return n;
}int Listen(int fd, int backlog)
{int n;if ((n = listen(fd, backlog)) < 0)perr_exit("listen error");return n;
}int Socket(int family, int type, int protocol)
{int n;if ((n = socket(family, type, protocol)) < 0)perr_exit("socket error");return n;
}ssize_t Read(int fd, void *ptr, size_t nbytes)
{ssize_t n;again:if ( (n = read(fd, ptr, nbytes)) == -1) {if (errno == EINTR)//如果是被信号中断,不应该退出goto again;elsereturn -1;}return n;
}ssize_t Write(int fd, const void *ptr, size_t nbytes)
{ssize_t n;again:if ( (n = write(fd, ptr, nbytes)) == -1) {if (errno == EINTR)goto again;elsereturn -1;}return n;
}int Close(int fd)
{int n;if ((n = close(fd)) == -1)perr_exit("close error");return n;
}/*参三: 应该读取固定的字节数数据*/
ssize_t Readn(int fd, void *vptr, size_t n)
{size_t nleft; //usigned int 剩余未读取的字节数ssize_t nread; //int 实际读到的字节数char *ptr;ptr = vptr;nleft = n;while (nleft > 0) {if ((nread = read(fd, ptr, nleft)) < 0) {if (errno == EINTR)nread = 0;elsereturn -1;} else if (nread == 0)break;nleft -= nread;ptr += nread;}return n - nleft;
}
/*:固定的字节数数据*/
ssize_t Writen(int fd, const void *vptr, size_t n)
{size_t nleft;ssize_t nwritten;const char *ptr;ptr = vptr;nleft = n;while (nleft > 0) {if ( (nwritten = write(fd, ptr, nleft)) <= 0) {if (nwritten < 0 && errno == EINTR)nwritten = 0;elsereturn -1;}nleft -= nwritten;ptr += nwritten;}return n;
}static ssize_t my_read(int fd, char *ptr)
{static int read_cnt;static char *read_ptr;static char read_buf[100];if (read_cnt <= 0) {
again:if ( (read_cnt = read(fd, read_buf, sizeof(read_buf))) < 0) {if (errno == EINTR)goto again;return -1;} else if (read_cnt == 0)return 0;read_ptr = read_buf;}read_cnt--;*ptr = *read_ptr++;return 1;
}ssize_t Readline(int fd, void *vptr, size_t maxlen)
{ssize_t n, rc;char c, *ptr;ptr = vptr;for (n = 1; n < maxlen; n++) {if ( (rc = my_read(fd, &c)) == 1) {*ptr++ = c;if (c == '\n')break;} else if (rc == 0) {*ptr = 0;return n - 1;} elsereturn -1;}*ptr = 0;return n;
}int tcp4bind(short port,const char *IP)
{struct sockaddr_in serv_addr;int lfd = Socket(AF_INET,SOCK_STREAM,0);bzero(&serv_addr,sizeof(serv_addr));if(IP == NULL){//如果这样使用 0.0.0.0,任意ip将可以连接serv_addr.sin_addr.s_addr = INADDR_ANY;}else{if(inet_pton(AF_INET,IP,&serv_addr.sin_addr.s_addr) <= 0){perror(IP);//转换失败exit(1);}}serv_addr.sin_family = AF_INET;serv_addr.sin_port = htons(port);// int opt = 1;//setsockopt(lfd, SOL_SOCKET, SO_REUSEADDR, &opt, sizeof(opt));Bind(lfd,(struct sockaddr *)&serv_addr,sizeof(serv_addr));return lfd;
}
wrap.h:
#ifndef __WRAP_H_
#define __WRAP_H_
#include <stdlib.h>
#include <stdio.h>
#include <unistd.h>
#include <errno.h>
#include <string.h>
#include <sys/socket.h>
#include <arpa/inet.h>
#include <strings.h>void perr_exit(const char *s);
int Accept(int fd, struct sockaddr *sa, socklen_t *salenptr);
int Bind(int fd, const struct sockaddr *sa, socklen_t salen);
int Connect(int fd, const struct sockaddr *sa, socklen_t salen);
int Listen(int fd, int backlog);
int Socket(int family, int type, int protocol);
ssize_t Read(int fd, void *ptr, size_t nbytes);
ssize_t Write(int fd, const void *ptr, size_t nbytes);
int Close(int fd);
ssize_t Readn(int fd, void *vptr, size_t n);
ssize_t Writen(int fd, const void *vptr, size_t n);
ssize_t my_read(int fd, char *ptr);
ssize_t Readline(int fd, void *vptr, size_t maxlen);
int tcp4bind(short port,const char *IP);
#endif
2.将这两个文件放到线程服务器源文件的同一目录中,后面需要用到
3.第一步:创建套接字并且绑定
int main(int argc,char *argv[])
由上可见,argc是用户输入终端的参数个数,argv[]表示用户输入终端的信息,argv[0]是./a.out,argv[1]是端口号,如果argc小于2,表示没有传入端口号,退出即可,如下所示:
if(argc < 2)
{printf("argc < 2??? \n ./a.out 8000 \n");return 0;
}
将传入的字符型端口转为short型,如下所示:
short port=atoi(argv[1]);
然后调用wrap.c中的创建套接字并绑定方法“tcp4bind”,参数NULL表示绑定本地所有的ip地址,调用完后返回一个监听套接字,如下所示:
int lfd = tcp4bind(port,NULL);//创建套接字 绑定
4.第二步:开始监听,一样用wrap的方法,如下所示:
Listen(lfd,128);
5.第三步:开始提取
建立一个结构体保存提取的客户端信息,如下所示:
struct sockaddr_in cliaddr;
调用wrap中的提取方法,将提取到的信息放到上面的结构体(只要看到ipv4的结构体,都要转成通配地址,用(struct sockaddr *)强转)中,len是cliaddr的大小,如下所示:
socklen_t len = sizeof(cliaddr);
int cfd = Accept(lfd,(struct sockaddr *)&cliaddr,&len);
6.主线程负责监听,子线程负责服务客户端
所以,提取成功后要创建一个子线程,如下所示:
pthread_t pthid;
pthread_create(&pthid,&attr,client_fun,info);
info是一个结构体,表示要传两个参数给子线程,结构体定义和初始化如下:
typedef struct c_info
{int cfd;struct sockaddr_in cliaddr;
}CINFO;CINFO *info;info = malloc(sizeof(CINFO));info->cfd = cfd;
info->cliaddr= cliaddr;
client_fun是线程回调函数,表示子线程针对客户端要干的事情,如下所示:
void* client_fun(void *arg)
{CINFO *info = (CINFO *)arg;char ip[16]="";printf("new client ip=%s port=%d\n",inet_ntop(AF_INET,&(info->cliaddr.sin_addr.s_addr),ip,16),ntohs(info->cliaddr.sin_port));while(1){char buf[1024]="";int count=0;count = read(info->cfd,buf,sizeof(buf));if(count < 0){perror("");break; }else if(count == 0){printf("client close\n");break;}else{printf("%s\n", buf);write(info->cfd,buf,count); }}close(info->cfd);free(info);
}
7.子线程工作完成后,如何回收?
设置一下线程分离属性就可以了,如下所示:
pthread_attr_t attr;
pthread_attr_init(&attr);
pthread_attr_setdetachstate(&attr,PTHREAD_CREATE_DETACHED);
在这里使用(&attr),如下所示:
pthread_create(&pthid,&attr,client_fun,info);
这样的话,子线程退出,系统会自动回收子线程!
8.“1_pthread_server.c”的完整代码如下所示:
#include <stdio.h>
#include <pthread.h>
#include "wrap.h"typedef struct c_info
{int cfd;struct sockaddr_in cliaddr;
}CINFO;void* client_fun(void *arg);int main(int argc, char *argv[])
{if(argc < 2){printf("argc < 2??? \n");return 0;}pthread_attr_t attr;pthread_attr_init(&attr);pthread_attr_setdetachstate(&attr,PTHREAD_CREATE_DETACHED);short port = atoi(argv[1]);int lfd = tcp4bind(port,NULL);//创建套接字 绑定 Listen(lfd,128);struct sockaddr_in cliaddr;socklen_t len = sizeof(cliaddr);CINFO *info;while(1){int cfd = Accept(lfd,(struct sockaddr *)&cliaddr,&len);char ip[16]="";pthread_t pthid;info = malloc(sizeof(CINFO));info->cfd = cfd;info->cliaddr= cliaddr;pthread_create(&pthid,&attr,client_fun,info);}return 0;
}void* client_fun(void *arg)
{CINFO *info = (CINFO *)arg;char ip[16]="";printf("new client ip=%s port=%d\n",inet_ntop(AF_INET,&(info->cliaddr.sin_addr.s_addr),ip,16),ntohs(info->cliaddr.sin_port));while(1){char buf[1024]="";int count=0;count = read(info->cfd,buf,sizeof(buf));if(count < 0){perror("");break; }else if(count == 0){printf("client close\n");break;}else{printf("%s\n", buf);write(info->cfd,buf,count); }}close(info->cfd);free(info);
}
退出vim编辑器,gcc编译一下:
gcc 1_pthread_server.c wrap.c -lpthread
开始运行,8008表示你给线程服务器设置的端口号:
./a.out 8008
另开一个终端,输入以下命令连接你的线程服务器:
nc xxx.xxx.xxx.xxx 8008
xxx.xxx.xxx.xxx表示你的线程服务器的ip地址
至此即可完成客户端与线程服务器的通信