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 vue2(标签-chrome|关键词-浏览器兼容)
  • ¥15 python网络流自动生成系统 医学领域
  • ¥15 sql查询仓库里都有什么
  • ¥15 代码的修改,添加和运行完善
  • ¥15 krpano-场景分组和自定义地图分组
  • ¥15 lammps Gpu加速出错
  • ¥15 关于PLUS模型中kapaa值的问题
  • ¥15 关于博途V17进行仿真时无法建立连接问题
  • ¥15 机器学习教材中的例题询问
  • ¥15 求.net core 几款免费的pdf编辑器