微信小程序的API可以說是越來越強大了辟汰,UDP通信也有了摔握。
近期,有個項目可能要用到小程序昂勒,剛好提前研究學習調(diào)研帕膜,順便寫個簡單例子總結一下灭美。
通信效果展示
小程序UDP通信這一塊可以說是很簡單了就一個UDPSocket實例剩胁。然后bind()方法綁定端口擒权,send()方法發(fā)送數(shù)據(jù)袱巨,close()方法關閉通信,onMessage()方法監(jiān)聽消息等等碳抄,具體可以去看文檔愉老。
既然是通信,那么至少得有兩個參與者剖效,這里我以小程序為Server端嫉入,QT應用程序為Client端。
小程序為Server端:
固定IP:不定
端口號:不定
小程序UDP通信璧尸,Server端蠻簡單:
創(chuàng)建UDPSocket實例咒林,bind()方法綁定端口,onListening()方法監(jiān)聽爷光,onMessage()方法接收消息垫竞,send()方法發(fā)送數(shù)據(jù),close()方法關閉通信蛀序,onMessage()方法監(jiān)聽消息等等欢瞪,具體可以去看官方文檔。
initUdpSocket() {
this.data.udpSocket = wx.createUDPSocket();
if (this.data.udpSocket === null) {
console.log('暫不支持')
return ;
}
const locationPort = this.data.udpSocket.bind()
this.setData({
'locationUrl.port': locationPort
})
this.data.udpSocket.onListening(function(res){
console.log('監(jiān)聽中Res ===' + res)
})
let that = this
this.data.udpSocket.onMessage(function (res) {
console.log('remoteInfo ===' + res.remoteInfo)
console.log('remoteInfo.size ===' + res.remoteInfo.size)
if (res.remoteInfo.size > 0) {
console.log('UDP接收數(shù)據(jù) ' + res.remoteInfo.size + ' 字節(jié):' + JSON.stringify(res, null, '\t'))
let unit8Arr = new Uint8Array(res.message);
let encodedString = String.fromCharCode.apply(null, unit8Arr);
let escStr = escape(encodedString);
let decodedString = decodeURIComponent(escStr);
console.log('str==='+decodedString)
let list = that.data.messageList
let obj = {
text: decodedString,
from: 1
}
list.push(obj)
that.setData({
messageList: list
})
}
})
},
sendMessage() {
if (this.data.mydata.isSend) {
return ;
}
this.data.mydata.isSend = true
let ip = this.data.mydata.remoteUrl.ip
let port = this.data.mydata.remoteUrl.port
let message = this.data.mydata.message
if (message.trim() === '') {
wx.showToast({
title: '請輸入內(nèi)容',
})
this.data.mydata.isSend = false
return ;
}
this.data.udpSocket.send({
address: ip,
port: port,
message: message
})
this.data.mydata.isSend = false
let list = this.data.messageList
let obj = {
text: message,
from : 2
}
list.push(obj)
this.setData({
messageList : list
})
},
QT應用程序為Client端:
固定IP:如哼拔,192.168.1.103
端口號:6510
QT端UDP通信引有,Server也簡單:
創(chuàng)建QUdpSocket
void AppUdp::createSocket()
{
if (mUdpSocket != nullptr)
{
delete mUdpSocket;
mUdpSocket = nullptr;
}
mUdpSocket = new QUdpSocket();
}
綁定端口:6510
void AppUdp::listen(unsigned short listenPort)
{
// udp端口監(jiān)聽(線程安全)
if (listenPort != 0)
{
appConfig->clientPort = listenPort;
}
// signalListenSuccess信號返回監(jiān)聽結果,listenSuccess屬性可獲取
emit signalSelfListenPort();
}
void AppUdp::slotSelfListenPort()
{
bool result = mUdpSocket->bind(QHostAddress::Any, appConfig->clientPort);
this->setListenSuccess(result);
if (result)
{
QLOG_INFO() << "bind success ======= Listen port:" + QString("%1").arg(appConfig->clientPort);
}
else
{
QLOG_FATAL() << "bind fail ======= Listen port:" + QString("%1").arg(appConfig->clientPort);
}
emit signalListenSuccess(result);
}
udp監(jiān)聽回調(diào)
void AppUdp::slotUdpSocketReceive()
{
while (mUdpSocket->hasPendingDatagrams())
{
QHostAddress targetaddr;
unsigned short targetPort;
QByteArray datagram;
datagram.resize(static_cast<int>(mUdpSocket->pendingDatagramSize()));
mUdpSocket->readDatagram(datagram.data(), datagram.size(), &targetaddr, &targetPort);
if (datagram.size() > 0)
{
emit signalUdpSocketReceiveData(targetaddr, targetPort, datagram);
}
}
}
QT端作了一個信息回饋倦逐,
void AppUdpClientServer::slotSelfWriteControl(const QByteArray data)
{
QHostAddress address;
address.setAddress(appConfig->serverIp);
qint64 result = mUdpSocket->writeDatagram(data, address, appConfig->serverPort);
if (result == -1)
{
QLOG_WARN() << "Send ip=" << appConfig->serverIp << "Send port=" << appConfig->serverPort << " result=" << result
<< " udpState=" << mUdpSocket->state();
createSocket();
result = mUdpSocket->writeDatagram(data, address, appConfig->serverPort);
if (result == -1)
{
QLOG_FATAL() << "Send ip=" << appConfig->serverIp << "Send port=" << appConfig->serverPort << " result=" << result
<< " udpState=" << mUdpSocket->state();
emit signalUdpSocketError();
}
}
}
回饋前譬正,需要在Client接收數(shù)據(jù)是解析,IP和端口號
void AppUdpServerControl::slotClienttReceiveData(QHostAddress ipAddr, unsigned short port, QByteArray bytes)
{
QMutexLocker locker(m_mutex);
QString qStrIpAddrTemp = ipAddr.toString();
QString qStrIpAddr;
int i = 0;
// 填充ip地址
for (i = 7; qStrIpAddrTemp[i] != '\0'; i++)
{
qStrIpAddr[i - 7] = qStrIpAddrTemp[i];
}
QLOG_INFO() << "Ip[" << qStrIpAddr << "]. ort[" << port << "]. Size[" << bytes.size() << "]." << endl;
QString keyCmd = QString(bytes);
appUdpClientServer->getAppConfig()->serverIp = qStrIpAddr;
appUdpClientServer->getAppConfig()->serverPort = port;
if ("1" == keyCmd)
{
// TODO 一鍵回原點
motorSystem->getSystemMotor()->getParentBoard()->returnHome();
}
else if ("2" == keyCmd)
{
// TODO 單軸回原點
motorSystem->getControl()->returnHome();
}
else if ("3" == keyCmd)
{
// TODO 下降5mm
motorSystem->getControl()->moveByType(5);
const QByteArray data = "中文zhongwen";
appUdpClientServer->udpWriteData(data);
}
QLOG_INFO() << "keyCmd == " << keyCmd << "]." << endl;
}
感謝大家看完微信小程序UDP通信篇檬姥,更多精彩等待下次創(chuàng)作曾我,你最大的支持就是:贊同+評論+贊賞+...,關注我健民。
另外抒巢,也歡迎大家關注我的個人公眾號 “聊者說”。