想用Qt做一个局域网聊天工具 实现私聊功能 求提供实现私聊功能的流程思路
2条回答 默认 最新
- NiceBlueChai 2018-06-30 01:58关注
局域网的话用UDP Socket编程就好了虽然丢包率较高
参考一下这个源码,
//发送方
#define _CRT_SECURE_NO_WARNINGS /* VS2013,2015需要这一行 */
#include
#include#include "osapi/osapi.h"
#include "Endian.h"int main()
{
printf("发送方: port=9000 ...\n");OS_SockAddr local("127.0.0.1", 9000); OS_UdpSocket sock; sock.Open(local, true); while(1) { // 输入回车后,测试开始 printf("Press enter to send: "); getchar(); // 发送测试数据 //char buf[] = "hello"; //sock.SendTo(buf, 5, OS_SockAddr("127.0.0.1", 9001)); unsigned int a = 0x12345678; unsigned char bytes[4]; // be itob_32be(a, bytes); sock.SendTo(bytes, 4, OS_SockAddr("127.0.0.1", 9001)); } // 关闭socket sock.Close(); return 0;
}
\接收方
#define _CRT_SECURE_NO_WARNINGS /* VS2013,2015需要这一行 */
#include
#include#include "osapi/osapi.h"
#include "Endian.h"/* UDP socket 测试
接收方: 9001
*/// 按十六进制,将buf中的数字按字节打印显示
void print_bytes(void* buf, int n)
{
unsigned char* bytes = (unsigned char*) buf;
for(int i=0; i<n; i++)
{
printf("%02X ", bytes[i]);
if( (i+1)%16 == 0) printf("\n");
}
}int main()
{
printf("接收方: port=9001 ...\n");OS_SockAddr local("127.0.0.1", 9001); OS_UdpSocket sock; sock.Open(local, true); while(1) { unsigned char buf[128]; OS_SockAddr peer; // 对方的地址 int n = sock.RecvFrom(buf, 128, peer); if(n <= 0) { break; } // 按字节打印接收到的数据 printf("Got :"); print_bytes(buf, n); unsigned int a = btoi_32be(buf); printf("Got a number: %08X \n", a); } // 关闭socket sock.Close(); return 0;
}
解决 无用评论 打赏 举报