今天写了一个qq间的UDP套接字通信,感觉UDP的要简单些,分享一下:
代码如下:
1、客户端
1 #include <stdio.h>
2 #include <stdlib.h>
3 #include <errno.h>
4 #include <string.h>
5 #include <sys/types.h>
6 #include <netinet/in.h>
7 #include <sys/socket.h>
8
9 #define SERVER_PORT 8003
10 #define MSG_BUF_SIZE 512
11 int port = SERVER_PORT;
12
13
14 int main(){
15 int sockfd;
16 int count = 0;
17 int flag;
18 char buf[MSG_BUF_SIZE];
19 struct sockaddr_in address;
20 sockfd = socket(AF_INET,SOCK_DGRAM,0);
21 if(sockfd == -1){
22 fprintf(stderr,"socket error");
23 exit(1);
24 }
25 memset(&address,0,sizeof(address));
26 address.sin_family = AF_INET;
27 address.sin_addr.s_addr = inet_addr("server");
28 address.sin_port = htons(port);
29 flag = 1;
30 do
31 {
32 sprintf(buf,"Packet %dn",count);
33 if(count > 30){
34 sprintf(buf,"overn");
35 flag = 0;
36 }
37 sendto(sockfd,buf,sizeof(buf),0,(struct sockaddr *)&address,sizeof(address));
38 count++;
39 }
40 while (flag);
41 // printf("%d\n",MAXFILE);
42
43 return 0;
2、服务器端
1 #include <stdio.h>
2 #include <stdlib.h>
3 #include <errno.h>
4 #include <string.h>
5 #include <sys/types.h>
6 #include <netinet/in.h>
7 #include <sys/socket.h>
8
9 #define SERVER_PORT 8003
10 #define MSG_BUF_SIZE 512
11
12 int port = SERVER_PORT;
13 char *hostname = "127.0.0.1";
14
15 int main(){
16 int sinlen;
17 char message[MSG_BUF_SIZE];
18 int sockfd;
19 struct sockaddr_in sin;
20 struct hostent *server_host_name;
21 sockfd = socket(PF_INET,SOCK_DGRAM,0);
22 if(sockfd == -1){
23 fprintf(stderr,"socket error");
24 exit(1);
25 }
26 server_host_name = gethostbyname("127.0.0.1");
27 bzero(&sin,sizeof(sin));
28 sin.sin_family = AF_INET;
29 sin.sin_port = htons(port);
30
31 if((bind(sockfd,(struct sockaddr *)&sin,sizeof(sin)))== -1){
32 fprintf(stderr,"bind error");
33 exit(1);
34 }
35 while(1){
36 sinlen = sizeof(sin);
37 recvfrom(sockfd,message,256,0,(struct sockaddr *)&sin,&sinlen);
38 printf("nData come from server:n%sn",message);
39 if(strncmp(message,"over",4)==0)break;
40 }
41 close(sockfd);
42 return 0;
43 }
这个程序还留下一个问题:我想让我们实验室中任意两台机器都可通信还没实现,只能在自己的机器上进行通信,放一放,过后几天解决, 还有其它任务。
最后简单做一下UDP与TCP的比较:
1、udp的服务器端只需要socket,bind就ok了,而tcp需要完整的四步。
2、udp的客户端不需要连接(用了也不会出错),socket之后直接通信即可。
OK,国庆长假结束。。