网络编程-UDP的服务器和客户端----keep on going never give up

  1 //**************************************服务器**********************************************
2 #include <stdio.h>
3 #include <stdlib.h>
4 #include <string.h>
5 #include <time.h>
6 #include <sys/types.h> /* See NOTES */
7 #include <sys/socket.h>
8 #include <netinet/in.h>
9 #include <netinet/ip.h> /* super*/
10 #include <arpa/inet.h>
11 #include <unistd.h>
12 int server_init();
13 int main(int argc,const char *argv[])
14 {
15 //服务器初始化
16 server_init();
17 //数据交互
18 return 0;
19 }
20 typedef struct sockaddr SA;
21 int server_init()
22 {
23 int sockfd,ret;
24 //创建套接字
25 sockfd=socket(AF_INET,SOCK_DGRAM,0);
26 if(sockfd==-1)
27 {
28 perror("socket");
29 return -1;
30 }
31 struct sockaddr_in seraddr;
32 seraddr.sin_family=AF_INET;
33 seraddr.sin_port=htons(8181);
34 seraddr.sin_addr.s_addr=htonl(INADDR_ANY);
35 //绑定套接字
36 ret=bind(sockfd,(SA*)&seraddr,sizeof(seraddr));
37 if(ret==-1)
38 {
39 perror("bind");
40 return -1;
41 }
42 printf("bind-------------\n");
43 char buf[32];
44 struct sockaddr_in cliaddr;
45 socklen_t len=sizeof(cliaddr);
46 while(1)
47 {
48 //接收数据
49 bzero(buf,sizeof(buf));
50 recvfrom(sockfd,buf,sizeof(buf),0,(SA*)&cliaddr,&len);
51 printf("ip:%s port:%d cli==%s\n",inet_ntoa(cliaddr.sin_addr),ntohs(cliaddr.sin_port),buf);
52 sendto(sockfd,"hello",6,0,(SA*)&cliaddr,sizeof(cliaddr));
53 }
54 close(sockfd);
55 return sockfd;
56 }
57 //**************************************客户端**********************************************
58 #include <stdio.h>
59 #include <stdlib.h>
60 #include <string.h>
61 #include <time.h>
62 #include <sys/types.h> /* See NOTES */
63 #include <sys/socket.h>
64 #include <netinet/in.h>
65 #include <netinet/ip.h> /* super*/
66 #include <arpa/inet.h>
67 #include <unistd.h>
68 int server_init();
69 int main(int argc,const char *argv[])
70 {
71
72 //服务器初始化
73 server_init();
74
75 //数据交互
76
77
78 return 0;
79 }
80
81 typedef struct sockaddr SA;
82
83 int server_init()
84 {
85 int sockfd,ret;
86 //创建套接字
87 sockfd=socket(AF_INET,SOCK_DGRAM,0);
88 if(sockfd==-1)
89 {
90 perror("socket");
91 return -1;
92 }
93 char buf[32];
94 struct sockaddr_in seraddr;
95 seraddr.sin_family=AF_INET;
96 seraddr.sin_port=htons(8181);
97 seraddr.sin_addr.s_addr=htonl(INADDR_ANY);
98 while(1)
99 {
100 sleep(2);
101 //接收数据
102 bzero(buf,sizeof(buf));
103 sendto(sockfd,"hello",24,0,(SA*)&seraddr,sizeof(seraddr));
104 recvfrom(sockfd,buf,sizeof(buf),0,NULL,NULL);
105 printf("buf==%s\n",buf);
106 }
107
108 close(sockfd);
109 return sockfd;
110 }
上一篇:阅读《名师讲坛--Android开发实战经典》


下一篇:yarn的工作原理