Socket更多的操作_CPP

 1 #define _CRT_SECURE_NO_WARNINGS /* VS2013,2015需要这一行 */
 2 #include <stdio.h>
 3 #include <string.h>
 4 
 5 #include "osapi/osapi.h"
 6 
 7 int main()
 8 {
 9     printf("发送方: port=9000 ...\n");
10 
11     OS_UdpSocket sock;
12     sock.Open();
13 
14 
15     while(1)
16     {
17         // 让用户输入一段文本
18         char buf[128];
19         printf("> ");
20         gets(buf);
21         int n = strlen(buf);
22 
23         // 发送
24         OS_SockAddr peer("127.0.0.1", 9001); // 对方地址
25         sock.SendTo(buf, n, peer);
26 
27         // 查看OS自动分配的端口号是多少
28         OS_SockAddr local;
29         sock.GetLocalAddr(local);
30         int port = local.GetPort();
31         printf("local port: %d \n", port);
32 
33         // 结束
34         if(strcmp("bye", buf) == 0)
35         {
36             break;
37         }
38     }
39 
40     // 关闭socket
41     sock.Close();
42     return 0;
43 }
 1 #define _CRT_SECURE_NO_WARNINGS /* VS2013,2015需要这一行 */
 2 #include <stdio.h>
 3 #include <string.h>
 4 
 5 #include "osapi/osapi.h"
 6 
 7 /* UDP socket 测试
 8     接收方: 9001
 9 */
10 
11 int main()
12 {
13     printf("接收方: port=9001 ...\n");
14     
15     OS_SockAddr local("127.0.0.1", 9001);
16     OS_UdpSocket sock;
17     if(sock.Open(local, false) < 0)
18     {
19         printf("无法创建socket! \n");
20         return -1;
21     }
22     
23     // 设置接收超时
24     //sock.SetOpt_RecvTimeout(3000);
25     // 设置成non-blocked方式
26     //sock.Ioctl_SetBlockedIo(false);
27 
28     while(1)
29     {
30         char buf[128];
31         OS_SockAddr peer; // 对方的地址
32         int n = sock.RecvFrom(buf, 128, peer);
33         //printf("got: %d bytes \n", n);
34 
35         if(n <= 0)
36         {            
37             break;;
38         }
39 
40         buf[n] = 0;
41         printf("Got: %s \n", buf);
42 
43         // 是谁发过来的?
44         std::string peer_ip = peer.GetIp_str();
45         int peer_port = peer.GetPort();
46         printf("From: %s:%d \n", peer_ip.c_str(), peer_port);
47 
48         // 结束
49         if(strcmp("bye", buf) == 0)
50         {
51             break;
52         }
53     }
54 
55     // 关闭socket
56     sock.Close();
57     return 0;
58 }

 

posted on 2017-12-25 12:38  Doctor_uee  阅读(181)  评论(0)    收藏  举报

导航