I am able to send and receive to two different programs running on same computer. But not able to do the same when running them on different computers. Both computers are on same Local area network. I am working on 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;
}
CodePudding user response:
You need to bind to QHostAddress::Any
in order to actually receive packets from outside the local machine. QHostAddress::LocalHost
will only receive traffic from the same physical machine.