QT------WebSocket ╰+哭是因爲堅強的太久メ 2023-10-17 21:29 24阅读 0赞 **前言:**关于websocket,前几天尝试着在qt里面用原生QTcpServer和QTcpSocket进行解析。最终是连接成功了,但是数据发送全乱码了,至今不知道这回事儿。 简单说下就是建立它们的握手:我们用html做客户端,qt做服务端 该部分摘自网友的,有兴趣的同学可以参考这里[点击打开链接][Link 1] handshake(握手) client请求: GET /chat HTTP/1.1 Host: server.example.com Upgrade: websocket Connection: Upgrade Sec-WebSocket-Key: dGhlIHNhbXBsZSBub25jZQ== Sec-WebSocket-Version: 13 server回复: HTTP/1.1 101 Switching Protocols Upgrade: websocket Connection: Upgrade Sec-WebSocket-Accept: s3pPLMBiTxaQ9kYGzzhZRbK+xOo= "dGhlIHNhbXBsZSBub25jZQ=="(Sec-WebSocket-Key)+"258EAFA5-E914-47DA-95CA-C5AB0DC85B11" 先SHA-1哈希,再用base64编码,得到"s3pPLMBiTxaQ9kYGzzhZRbK+xOo=" 其中"258EAFA5-E914-47DA-95CA-C5AB0DC85B11"为固定字符串,至于为什么就没有深究了。上面的哈希、bas64在qt里面都很好实现: QString clent_str="dGhlIHNhbXBsZSBub25jZQ=="; QString sever_str=QCryptographicHash::hash(clent_str.toLocal8Bit(), QCryptographicHash::Sha1).toBase64(); 接下来说说QT自带的QWebSocketServer、QWebSocket,这里有QT已经封装过的,会自动握手,减少了我们的工作量。我们在头文件里面声明: public: QWebSocketServer* websocketsever2=NULL; QWebSocket* websocket2=NULL; public slots: void new_sockeconnection2();//新连接到来 void read_websocket_massage2(QString message);//接收websocket消息 在cpp面定义 //构造函数里面new出sever,并监听 MainWindow::MainWindow(QWidget *parent) : QMainWindow(parent), ui(new Ui::MainWindow) { ui->setupUi(this); // websocketsever=new QTcpServer(this); // websocketsever->listen(QHostAddress::Any,9547); // connect(websocketsever,SIGNAL(newConnection()),this,SLOT(new_sockeconnection())); websocketsever2=new QWebSocketServer(QStringLiteral("Echo Server"), QWebSocketServer::NonSecureMode, this); websocketsever2->listen(QHostAddress::Any,9547);//监听端口9547 connect(websocketsever2,SIGNAL(newConnection()),this,SLOT(new_sockeconnection2()));//当有新连接到来,执行new_sockeconnection2()函数 } //新连接到来 void MainWindow::new_sockeconnection2() { if(websocketsever2!=NULL) { ui->textEdit->append(QString::fromLocal8Bit("新的连接!")); websocket2=websocketsever2->nextPendingConnection(); } if(websocket2!=NULL) { connect(websocket2,SIGNAL(textMessageReceived(QString)),this, SLOT(read_websocket_massage2(QString)));//当有消息到来,执行read_websocket_massage2(QString)函数接收消息 } } //接收到消息 void MainWindow::read_websocket_massage2(QString message) { QWebSocket *pClient = qobject_cast<QWebSocket *>(sender()); ui->textEdit->append(message); qDebug() << "Message received:" << message; if (pClient) { // pClient->sendTextMessage(message); } } //发送消息到网页 void MainWindow::send_websocket_massage2() { QString adasd="sadadadada"; adasd=ui->textEdit_2->toPlainText(); websocket2->sendTextMessage(adasd); } HTML文件: <html> <head> <title>WebSocket Echo Client</title> </head> <meta charset="UTF-8"> <body> <h1>WebSocket Echo Client</h1> <p> <button onClick="initWebSocket();">Connect</button> <button onClick="stopWebSocket();">Disconnect</button> <button onClick="checkSocket();">State</button> </p> <p> <textarea id="debugTextArea" style="width:400px;height:200px;"></textarea> </p> <p> <input type="text" id="inputText" οnkeydοwn="if(event.keyCode==13)sendMessage();"/> <button onClick="sendMessage();">Send</button> </p> <script type="text/javascript"> var debugTextArea = document.getElementById("debugTextArea"); function debug(message) { debugTextArea.value += message + "\n"; debugTextArea.scrollTop = debugTextArea.scrollHeight; } function sendMessage() { var msg = document.getElementById("inputText").value; if ( websocket != null ) { document.getElementById("inputText").value = ""; websocket.send( msg ); console.log( "string sent :", '"'+msg+'"' ); } } var wsUri = "ws://192.168.0.15:9547"; var websocket = null; function initWebSocket() { try { if (typeof MozWebSocket == 'function') WebSocket = MozWebSocket; if ( websocket && websocket.readyState == 1 ) websocket.close(); websocket = new WebSocket( wsUri ); websocket.onopen = function (evt) { debug("连接成功"); }; websocket.onclose = function (evt) { debug("断开连接"); }; websocket.onmessage = function (evt) { console.log( "Message received :", evt.data ); debug( evt.data ); }; websocket.onerror = function (evt) { debug('ERROR: ' + evt.data); }; } catch (exception) { debug('ERROR: ' + exception); } } function stopWebSocket() { if (websocket) websocket.close(); } function checkSocket() { if (websocket != null) { var stateStr; switch (websocket.readyState) { case 0: { stateStr = "CONNECTING"; break; } case 1: { stateStr = "OPEN"; break; } case 2: { stateStr = "CLOSING"; break; } case 3: { stateStr = "CLOSED"; break; } default: { stateStr = "UNKNOW"; break; } } debug("WebSocket state = " + websocket.readyState + " ( " + stateStr + " )"); } else { debug("WebSocket is null"); } } </script> </body> </html> [![20180522210641611][]][20180522210641611 1] [Link 1]: http://www.cnblogs.com/danju/p/3691643.html [20180522210641611]: https://img-blog.csdn.net/20180522210641611 [20180522210641611 1]: https://mp.csdn.net/postedit/2H5%29OCN%60$%29NL@F9A5I%5D%5DL.png%29
还没有评论,来说两句吧...