【问题标题】:Qt UDpsocket working on same computer but not on two computers on same networkQt UDpsocket 在同一台计算机上工作,但不在同一网络上的两台计算机上工作
【发布时间】:2021-12-02 21:08:33
【问题描述】:

我能够发送和接收运行在同一台计算机上的两个不同程序。但是在不同的计算机上运行它们时不能做同样的事情。两台计算机都在同一个局域网上。我正在使用 Windows 10。

#include "communicationmanager.h"

communicationManager::communicationManager(int portNumber,int socketRole)
{
    //socketRole:0=Sender 1=Reciever
    //socket = new QUdpSocket(this);
    PortNumber = portNumber;
    socket = new QUdpSocket(this);
    if(socketRole == 1)
    {
        socket->bind(QHostAddress::LocalHost,PortNumber);
        connect(socket, SIGNAL(readyRead()), this, SLOT(recieve()));
    }
}

communicationManager::~communicationManager()
{
    //delete socket;
}

void communicationManager::prepareMessage(QString command,QString message,int recieverID)
{
   
    Command = command;
    Message = message;
    recieverID = recieverID;
}

void communicationManager::send()
{
    QByteArray datagram;
    QDataStream out(&datagram, QIODevice::WriteOnly);
    out.setVersion(QDataStream::Qt_5_13);
    out<<Command<<Message<<recieverID;
    socket->writeDatagram(datagram, QHostAddress::LocalHost, PortNumber);

}

void communicationManager::recieve()//For recieving data
{
    qDebug()<<"recieve";
    QByteArray datagram;

    do
    {
        datagram.resize(socket->pendingDatagramSize());
        socket->readDatagram(datagram.data(), datagram.size());
    } while (socket->hasPendingDatagrams());


    QDataStream in(&datagram, QIODevice::ReadOnly);
    QString command;
    QString message;
    int recieverID;
    in >>command>>message>>recieverID;
}

【问题讨论】:

  • 嘿,你用几种不同的语言标记了这个问题,即C#C++ 和(隐式)Python,请不要用与你的问题无关的语言标记你的问题/ 代码,因为它会吸引反对票,因为人们会看到你的问题,这不一定能帮助你(例如,我的 C++ 知识基本上不存在)。请记住,您也不需要为您的问题添加尽可能多的标签

标签: c++ qt networking


【解决方案1】:

您需要绑定到QHostAddress::Any 才能真正接收来自本地计算机外部的数据包。 QHostAddress::LocalHost 只会接收来自同一台物理机的流量。

【讨论】:

  • 我必须在发件人处使用 QHostAddress:: 广播吗?正如您所说的 localhost 是用于同一台物理机的。我认为 localhost 是用于同一本地网络的。
  • 我试过 QHostAddress:: Broadcast at sender.It 成功了。谢谢。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2018-12-29
  • 1970-01-01
相关资源
最近更新 更多