套接字编程(四)-----多线程

基于多线程服务器的优缺点

优点:开销小
缺点:不稳定

服务器端:

#include
#include
#include
#include
#include
#include
#include
#include
void* handleRequest(void* arg)
{
    char buf[10240];
  int sock=(int)arg;
  while(1)
  {
    ssize_t s=read(sock,buf,sizeof(buf)-1);
    //success
    if(s>0)
    {
      buf[s]=0;
      printf("%s\n",buf);
      const char *msg= "HTTP/1.1 200 OK\r\n\r\n

This is title

\r\n"
; write(sock,msg,strlen(msg)); break; } else if(s==0) { printf("client is quit!\n"); break; } else { perror("read"); break; } } close(sock); } int startup(const char *_ip,int _port) { //create socket int sock=socket(AF_INET,SOCK_STREAM,0); if(sock<0) { perror("socket"); return 2; } int flag=1; setsockopt(sock,SOL_SOCKET,SO_REUSEADDR,&flag,sizeof(flag)); //bind struct sockaddr_in local; local.sin_family=AF_INET; local.sin_port=htons(_port); local.sin_addr.s_addr=inet_addr(_ip); if(bind(sock,(struct sockaddr*)&local,sizeof(local))<0) { perror("bind"); return 3; } //listen if(listen(sock,10)<0) { perror("listen"); return 4; } return sock; } static void usage(char *proc) { printf("usage:%s [server_ip] [server_port]",proc); } int main(int argc, char *argv[]) { if(argc!=3) { usage(argv[0]); return 1; } int listen_sock=startup(argv[1],atoi(argv[2])); struct sockaddr_in peer; socklen_t len=sizeof(peer); while(1) { int new_sock=accept(listen_sock,(struct sockaddr*)&peer,&len); if(new_sock<0) { perror("accept"); continue; } printf("client ip:%s,port:%d\n",inet_ntoa(peer.sin_addr),ntohs(peer.sin_port)); pthread_t id; pthread_create(&id,NULL,handleRequest,(void*)new_sock); pthread_detach(id); } return 0; }

你可能感兴趣的:(计算机网络)