linux多线程
来源:互联网 发布:双录取很坑人 知乎 编辑:程序博客网 时间:2024/06/04 19:25
1、服务器代码
#include<stdio.h>#include<sys/types.h>#include<sys/socket.h>#include<string.h>#include<stdlib.h>#include<arpa/inet.h>#include<netinet/in.h>int startup(const char *_ip,int _port){int sock = socket(AF_INET,SOCK_STREAM,0);if(sock < 0){perror("socket");exit(1);}struct sockaddr_in local;local.sin_family = AF_INET;local.sin_port = htons(_port);local.sin_addr.s_addr = inet_addr(_ip);int opt = 1;setsockopt(sock,SOL_SOCKET,SO_REUSEADDR,&opt,sizeof(opt));if(bind(sock,(struct sockaddr*)&local,sizeof(local)) < 0){perror("bind");exit(2);}if(listen(sock,10) < 0){perror("listen");exit(3);}return sock;}static void usage(const char *proc){printf("[local_ip][local_port]\n",proc);}void *handleRequst(void *arg){char buf[10240];int sock = (int)arg;while(1){ssize_t s = read(sock,buf,sizeof(buf)-1);if(s > 0){buf[s] = 0;printf("%s\n",buf);const char* msg = "HTTP/1.0 200 OK\r\n\r\n<html><h1>hello world</h1></html>\r\n";write(sock,msg,strlen(msg));break;}else if(s == 0){printf("client quit!\n");break;}else{perror("read");break;}}}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;while(1){socklen_t len = sizeof(peer);int new_sock = accept(listen_sock,(struct sockaddr*)&peer,&len);if(new_sock < 0){perror("accept");continue;}printf("new client,ip-port->%s:%d\n",inet_ntoa(peer.sin_addr),ntohs(peer.sin_port));pthread_t id;pthread_create(&id,NULL,handleRequst,(void*)new_sock);pthread_detach(id);}return 0;}
阅读全文
0 0
- linux多线程
- linux多线程
- Linux多线程
- linux多线程
- linux多线程
- linux多线程~
- LINUX多线程
- linux多线程
- Linux多线程
- linux多线程
- linux多线程
- linux多线程
- linux多线程
- linux 多线程
- Linux多线程
- linux 多线程
- Linux多线程
- LINUX 多线程
- lintcode 56 两数之和
- USACO-Section1.2 palsquare[字符处理]
- 左侧显示分类栏
- 598. Range Addition II
- Maven学习(一)
- linux多线程
- ROS-笔记
- 呼吸灯 串口 SGM3146
- LeetCode 40. Combination Sum II
- 正则表达式
- 如何进行CRC校验
- 341. Flatten Nested List Iterator
- 对象标识符和对象引用+对象标识符+对象引用+为对象引用插入数据+查询对象引用OID对应的实际值+更新对象引用+删除对象引用
- BIEE 11g 使用叙述视图实现复杂中国式表格一例