首页 技术 正文
技术 2022年11月14日
0 收藏 369 点赞 3,103 浏览 1636 个字
 1 #include <stdio.h>
2 #include <stdlib.h>
3 #include <string.h>
4 #include <time.h>
5 #include <sys/types.h> /* See NOTES */
6 #include <sys/socket.h>
7 #include <netinet/in.h>
8 #include <netinet/ip.h>
9 #include <arpa/inet.h>
10 #include <unistd.h>
11 #include <sys/wait.h>
12 #include <pthread.h>
13
14 int Server_init(void);
15 typedef struct sockaddr SA;
16
17 void *callback(void* confd);
18 int main(int argc,const char *argv[])
19 {
20 int sockfd;
21 //初始化套接字
22 sockfd=Server_init();
23
24 return 0;
25 }
26
27 int Server_init(void)
28 {
29 //创建套接字
30 int sockfd=socket(AF_INET,SOCK_STREAM,0);
31 if(sockfd==-1)
32 {
33 perror("sockfd");
34 return -1;
35 }
36
37 //绑定套接字
38 struct sockaddr_in seraddr;
39 seraddr.sin_family=AF_INET;
40 seraddr.sin_port=htons(8080);
41 seraddr.sin_addr.s_addr=htonl(INADDR_ANY);
42 int ret=bind(sockfd,(SA*)&seraddr,sizeof(seraddr));
43 if(ret==-1)
44 {
45 perror("bind");
46 return -1;
47 }
48
49 //监听
50 ret=listen(sockfd,0);
51 if(ret==-1)
52 {
53 perror("listen");
54 return -1;
55 }
56 printf("listen--successful\n");
57 //接通
58 struct sockaddr_in cliaddr;
59 socklen_t len=sizeof(cliaddr);
60 while(1)
61 {
62 int confd=accept(sockfd,(SA*)&cliaddr,&len);
63 if(confd==-1)
64 {
65 perror("accept");
66 return -1;
67 }
68 printf("accept--successful %s %d\n",inet_ntoa(cliaddr.sin_addr),ntohs(cliaddr.sin_port));
69 pthread_t thread_id;
70 int ret=pthread_create(&thread_id,NULL,callback,(void*)confd);    //把连接套接字直接发过去
71 if(ret==-1)
72 {
73 perror("pthread_create");
74 return -1;
75 }
76 pthread_detach(thread_id);
77 }
78 close(sockfd);
79 }
80
81 void *callback(void* confd)    
82 {
83 int id=(int)confd;  //注意:关闭套接字时,需要一个局部变量
84 while(1)
85 {
86 char buf[64];
87 bzero(buf,sizeof(buf));
88 strcpy(buf,"hello ,this is server");
89 //发送数据
90 send(id,buf,sizeof(buf),0);
91 }
92 close(id);
93 pthread_exit(NULL);
94 }

  

相关推荐
python开发_常用的python模块及安装方法
adodb:我们领导推荐的数据库连接组件bsddb3:BerkeleyDB的连接组件Cheetah-1.0:我比较喜欢这个版本的cheeta…
日期:2022-11-24 点赞:878 阅读:9,031
Educational Codeforces Round 11 C. Hard Process 二分
C. Hard Process题目连接:http://www.codeforces.com/contest/660/problem/CDes…
日期:2022-11-24 点赞:807 阅读:5,520
下载Ubuntn 17.04 内核源代码
zengkefu@server1:/usr/src$ uname -aLinux server1 4.10.0-19-generic #21…
日期:2022-11-24 点赞:569 阅读:6,368
可用Active Desktop Calendar V7.86 注册码序列号
可用Active Desktop Calendar V7.86 注册码序列号Name: www.greendown.cn Code: &nb…
日期:2022-11-24 点赞:733 阅读:6,148
Android调用系统相机、自定义相机、处理大图片
Android调用系统相机和自定义相机实例本博文主要是介绍了android上使用相机进行拍照并显示的两种方式,并且由于涉及到要把拍到的照片显…
日期:2022-11-24 点赞:512 阅读:7,781
Struts的使用
一、Struts2的获取  Struts的官方网站为:http://struts.apache.org/  下载完Struts2的jar包,…
日期:2022-11-24 点赞:671 阅读:4,860