• 多线程服务器



    /*
    ** server.c ***/ #include<stdio.h> #include<fcntl.h> #include<string.h> #include<netinet/in.h> #include<arpa/inet.h> #include<signal.h> #include<sys/wait.h> #include<ctype.h> #include<unistd.h> #include<pthread.h> #include"wrap.h" #define MAXLINE 8192 #define SERV_PORT 8000 struct s_info { struct sockaddr_in cliaddr; int connfd; }; void *do_work(void *arg) { int n,i; struct s_info *ts = (struct s_info*)arg; char buf[MAXLINE]; char str[INET_ADDRSTRLEN]; while(1) { n = Read(ts->connfd,buf,MAXLINE) ; if( 0 == n) { printf("the client %d close... ",ts->connfd) ; break; } printf("received from %s at PORT:%d ", inet_ntop(AF_INET,&(*ts).cliaddr.sin_addr,str,sizeof(str)), ntohs((*ts).cliaddr.sin_port)); for(i = 0 ; i < n; i++) buf[i] = toupper(buf[i]); Write(STDOUT_FILENO,buf,n); Write(ts->connfd,buf,n); } close(ts->connfd); return (void*)0; } int main() { struct sockaddr_in servaddr,cliaddr; socklen_t cliaddr_len; int listenfd,connfd; pthread_t tid; struct s_info ts[256]; int i = 0; listenfd = Socket(AF_INET,SOCK_STREAM,0); bzero(&servaddr,sizeof(servaddr)); servaddr.sin_family = AF_INET; servaddr.sin_port = htons(SERV_PORT); servaddr.sin_addr.s_addr = htonl(INADDR_ANY); //inet_pton(AF_INET,"192.168.0.1",&serv_addr.sin_addr.s_addr); Bind(listenfd,(struct sockaddr *)&servaddr,sizeof(servaddr)); Listen(listenfd,128); printf("Accepting client connect ... "); while(1) { cliaddr_len = sizeof(cliaddr); connfd = Accept(listenfd,(struct sockaddr *)&cliaddr,&cliaddr_len); ts[i].cliaddr = cliaddr; ts[i].connfd = connfd; pthread_create(&tid,NULL,do_work,(void *)&ts[i]); pthread_detach(tid); i++; } return 0; }
    /***
    makefile
    ***/
    src = $(wildcard *.c)
    obj = $(patsubst %.c, %.o, $(src))
    
    all: server client
    
    server: server.o wrap.o
        gcc server.o wrap.o -o server -Wall -lpthread
    client: client.o wrap.o
        gcc client.o wrap.o -o client -Wall -lpthread
    
    %.o:%.c
        gcc -c $< -Wall
    
    .PHONY: clean all
    clean: 
        -rm -rf server client $(obj)

    makefile主要是添加了-lpthread线程库

    这是服务器编写代码,客户端代码可以使用上篇,也可以使用命令:nc + IP地址+端口号来代替客户端作用

    运行结果:

    还使用了wrap.c和wrap.h文件,在上篇博客有,这里就重复使用了。

  • 相关阅读:
    asp.net一些学习文档
    如何让baidu,google,yahoo搜索到自己的网页?
    [转] 驾校考试秘笈 不用看书就能通过!! 暂时不考也先留着 别等着急的时候没处找
    C++辅助工具 ZZ
    C/C++性能优化 ZZ
    Optimizing C and C++ Code ZZ
    《中国2030》报告解读创新兼谈研发经费 转载
    春三月,此谓发陈,天地俱生,万物以荣ZZ
    字符串翻转/反转(reverse a CStyle String)
    经典数字信号处理图书的个人评述ZZ
  • 原文地址:https://www.cnblogs.com/wanghao-boke/p/11409488.html
Copyright © 2020-2023  润新知