创建UDP客户端:
#define SAK_HOST_ADDRESS_ANY \"\\\"Any\\\"\"
mUdpSocket = new QUdpSocket;
bool bindResult = false;
if (specifyLocalInfo) {
if (localHost.compare(SAK_HOST_ADDRESS_ANY) == 0) {
bindResult = mUdpSocket->bind(QHostAddress::Any,
localPort,
QUdpSocket::ShareAddress);
} else {
bindResult = mUdpSocket->bind(QHostAddress(localHost),
localPort,
QUdpSocket::ShareAddress);
}
} else {
bindResult = mUdpSocket->bind();
}
if (bindResult){
QString info = mUdpSocket->localAddress().toString();
info.append(":");
info.append(QString::number(mUdpSocket->localPort()));
emit clientInfoChanged(info);
#if 0
SAKStructAdvancedCtx ctx = advancedCtx();
for (int i = 0; i < ctx.multicastCtxVector.length(); i++) {
SAKStructMulticastCtx multicastCtx = ctx.multicastCtxVector.at(i);
QHostAddress address(multicastCtx.address);
if (!mUdpSocket->joinMulticastGroup(address)) {
const QString info = QString("Can not join multicast group");
emit errorOccurred(info);
}
}
#endif
}else{
QString errorString = tr("Binding failed:") + mUdpSocket->errorString();
emit errorOccurred(errorString);
return false;
}
if (mUdpSocket->open(QUdpSocket::ReadWrite)){
connect(mUdpSocket, &QUdpSocket::readyRead, this, [=](){
emit readyRead(SAKDeviceProtectedSignal());
}, Qt::DirectConnection);
} else {
QString errorString = tr("Open device failed:") + mUdpSocket->errorString();
emit errorOccurred(errorString);
return false;
}
创建UDP服务器
mUdpServer = new QUdpSocket;
if (!mUdpServer->bind(QHostAddress(parameters.serverHost),
parameters.serverPort,
QUdpSocket::ShareAddress)) {
QString errorString = tr("Binding failed:") + mUdpServer->errorString();
emit errorOccurred(errorString);
return false;
} else {
QStringList hosts = multicastParameters();
for (int i = 0; i < hosts.length(); i++) {
const QString host = hosts.at(i);
if (!mUdpServer->joinMulticastGroup(QHostAddress(host))) {
qDebug() << QString("Join multicast group(%1) filed:")
.arg(host);
}
}
connect(mUdpServer, &QUdpSocket::readyRead,
this, [=](){
emit readyRead(SAKDeviceProtectedSignal());
}, Qt::DirectConnection);
}