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;
    

    }

    评论

报告相同问题?

悬赏问题

  • ¥50 永磁型步进电机PID算法
  • ¥15 sqlite 附加(attach database)加密数据库时,返回26是什么原因呢?
  • ¥88 找成都本地经验丰富懂小程序开发的技术大咖
  • ¥15 如何处理复杂数据表格的除法运算
  • ¥15 如何用stc8h1k08的片子做485数据透传的功能?(关键词-串口)
  • ¥15 有兄弟姐妹会用word插图功能制作类似citespace的图片吗?
  • ¥200 uniapp长期运行卡死问题解决
  • ¥15 latex怎么处理论文引理引用参考文献
  • ¥15 请教:如何用postman调用本地虚拟机区块链接上的合约?
  • ¥15 为什么使用javacv转封装rtsp为rtmp时出现如下问题:[h264 @ 000000004faf7500]no frame?