通信协议
1 #define _CRT_SECURE_NO_WARNINGS /* VS2013,2015需要这一行 */ 2 #include <stdio.h> 3 #include <string.h> 4 5 #include "osapi/osapi.h" 6 7 /* 发送文件 */ 8 9 int main() 10 { 11 printf("发送方: port=9000 ...\n"); 12 13 OS_UdpSocket sock; 14 sock.Open(); 15 16 // 回车后,开始传送 17 printf("press enter to send ..."); 18 getchar(); 19 20 FILE* fp = fopen("123.rar", "rb");//传输的文件 21 unsigned char buf[1024 + 16];// unsigned char 22 23 OS_SockAddr peer("127.0.0.1", 9001); // 对方地址 24 25 // 指令:开始传送 26 buf[0] = 0x01; 27 sock.SendTo(buf, 16, peer); 28 29 int count = 0; 30 while(1) 31 { 32 int n = fread(buf + 16, 1, 1024, fp); 33 if(n <= 0) break; 34 35 // 数据包指令 36 buf[0] = 0x02; 37 sock.SendTo(buf, n + 16, peer); 38 39 // 接收应答 40 sock.RecvFrom(buf, 16, peer); 41 42 //OS_Thread::Msleep(50); //udp模式传输控制速度防止丢包 43 printf("send data pcket , count=%d !\n", ++count); 44 } 45 46 // 指令:结束传送 47 buf[0] = 0xFF; 48 sock.SendTo(buf, 16, peer); 49 50 printf("发送完成,按回车关闭!\n"); 51 getchar(); 52 53 54 fclose(fp); 55 // 关闭socket 56 sock.Close(); 57 return 0; 58 }
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 /* 接收文件 */ 12 13 // 按十六进制,将buf中的数字按字节打印显示 14 void print_bytes(void* buf, int n) 15 { 16 unsigned char* bytes = (unsigned char*) buf; 17 for(int i=0; i<n; i++) 18 { 19 printf("%02X ", bytes[i]); 20 if( (i+1)%16 == 0) printf("\n"); 21 } 22 } 23 24 int main() 25 { 26 printf("接收方: port=9001 ...\n"); 27 28 OS_SockAddr local("127.0.0.1", 9001); 29 OS_UdpSocket sock; 30 sock.Open(local, true); 31 32 FILE* fp = fopen("copy.rar", "wb"); 33 unsigned char buf[1024 + 16]; 34 35 int count = 0; 36 while(1) 37 { 38 OS_SockAddr peer; // 对方的地址 39 int n = sock.RecvFrom(buf, sizeof(buf), peer); 40 41 if(n <= 0) 42 { 43 break; 44 } 45 46 // 应答 47 sock.SendTo("OK", 2, peer); 48 49 if(buf[0] == 0x01) 50 { 51 printf("传输开始\n"); 52 continue; 53 } 54 else if(buf[0] == 0xFF) // 注意:buf必须为unsigned 55 { 56 printf("传输结束\n"); 57 break; 58 } 59 else 60 { 61 fwrite(buf+16, 1, n-16, fp);//buf+16后面是数据 62 printf("Got: %d bytes \n", n); 63 //print_bytes(buf, 16); 64 printf("Packets = %d !\n", ++count); 65 } 66 } 67 68 fclose(fp); 69 70 // 关闭socket 71 sock.Close(); 72 return 0; 73 }
posted on 2017-12-27 12:35 Doctor_uee 阅读(194) 评论(0) 收藏 举报
浙公网安备 33010602011771号