jueqidexiaobai 2018-06-30 00:13 采纳率: 0%
浏览 1684
已结题

Qt 局域网聊天工具 私聊

想用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;
    

    }

    评论

报告相同问题?

悬赏问题

  • ¥15 stata安慰剂检验作图但是真实值不出现在图上
  • ¥15 c程序不知道为什么得不到结果
  • ¥40 复杂的限制性的商函数处理
  • ¥15 程序不包含适用于入口点的静态Main方法
  • ¥15 素材场景中光线烘焙后灯光失效
  • ¥15 请教一下各位,为什么我这个没有实现模拟点击
  • ¥15 执行 virtuoso 命令后,界面没有,cadence 启动不起来
  • ¥50 comfyui下连接animatediff节点生成视频质量非常差的原因
  • ¥20 有关区间dp的问题求解
  • ¥15 多电路系统共用电源的串扰问题