PyQt5 中的 WebSocket 服务器,显然是正确的,但我无法连接
WebSocket server in PyQt5, apparently correct, however I can not connect
我需要在 pyqt5 中创建一个 websocket 服务器,请阅读 5.3 版本的文档,其中包含所有必需的类,请按照 C ++ 中的这些示例
http://doc.qt.io/qt-5/qtwebsockets-examples.html
这是结果:
from PyQt5 import QtCore, QtWebSockets, QtNetwork
class MyServer(QtCore.QObject):
def __init__(self, parent=None):
super(QtCore.QObject, self).__init__(parent)
self.server = QtWebSockets.QWebSocketServer('My Socket', QtWebSockets.QWebSocketServer.NonSecureMode)
if self.server.listen(QtNetwork.QHostAddress.LocalHost, 1302):
print('Connected: '+self.server.serverName()+' : '+self.server.serverAddress().toString()+':'+str(self.server.serverPort()))
else:
print('error')
self.server.newConnection.connect(self.onNewConnection)
print(self.server.isListening())
def onNewConnection(self):
print(self.sender())
print("inside")
self.server.textMessageReceived.connect(self.processTextMessage)
self.server.binaryMessageReceived.connect(self.processBinaryMessage)
self.server.disconnected.connect(self.socketDisconnected)
def processTextMessage(self, message):
print(message)
def processBinaryMessage(self, message):
print(message)
def socketDisconnected(self):
print('out')
if __name__ == "__main__":
import sys
app = QtWidgets.QApplication(sys.argv)
MyServer()
sys.exit(app.exec_())
当运行 isListening 方法时,returns 正确,这让我相信这段代码是正确的,但是我尝试通过 javascript 客户端(html5 websocket)连接并且它 returns 我是服务器连接错误,当我尝试通过 telnet (telnet localhost 1302) 拍摄服务器时也会发生同样的情况。
实际上信号有问题:您不必连接服务器,但需要连接 clientConnections:
def onNewConnection(self):
clientConnection = self.server.nextPendingConnection()
clientConnection.disconnected.connect(clientConnection.deleteLater)
print(self.sender())
print("inside")
clientConnection.textMessageReceived.connect(self.processTextMessage)
clientConnection.binaryMessageReceived.connect(self.processBinaryMessage)
self.server.disconnected.connect(self.socketDisconnected)
然后我尝试使用 html5 客户端:
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
<title>WebSocket Test</title>
<script>
//var wsUri = "ws://echo.websocket.org/";
var wsUri = "ws://127.0.0.1:1302";
var output;
function init() { output = document.getElementById("output"); testWebSocket(); }
function testWebSocket() {
websocket = new WebSocket(wsUri);
websocket.onopen = function(evt) { onOpen(evt) };
websocket.onclose = function(evt) { onClose(evt) };
websocket.onmessage = function(evt) { onMessage(evt) };
websocket.onerror = function(evt) { onError(evt) }; }
function onOpen(evt) { writeToScreen("CONNECTED"); doSend("WebSocket rocks"); }
function onClose(evt) { writeToScreen("DISCONNECTED"); }
function onMessage(evt) {
writeToScreen('<span style="color: blue;">RESPONSE: ' + evt.data+'</span>'); websocket.close();
}
function onError(evt) { writeToScreen('<span style="color: red;">ERROR:</span> ' + evt.data); }
function doSend(message) {
writeToScreen("SENT: " + message); websocket.send(message);
}
function writeToScreen(message) {
var pre = document.createElement("p");
pre.style.wordWrap = "break-word";
pre.innerHTML = message;
output.appendChild(pre); }
window.addEventListener("load", init, false);
</script>
</head>
<body>
<h2>WebSocket Test</h2>
<div id="output"></div>
</body>
</html>
然后我们至少在服务器端连接和打印客户端消息"WebSocket rocks"。但是代码还有待完善
感谢回复,代码中还有其他错误,如果有人需要,最后的代码:
from PyQt5 import QtCore, QtWebSockets, QtNetwork, QtWidgets
class MyServer(QtCore.QObject):
def __init__(self, parent):
super(QtCore.QObject, self).__init__(parent)
self.clients = []
self.server = QtWebSockets.QWebSocketServer(parent.serverName(), parent.secureMode(), parent)
if self.server.listen(QtNetwork.QHostAddress.LocalHost, 1302):
print('Connected: '+self.server.serverName()+' : '+self.server.serverAddress().toString()+':'+str(self.server.serverPort()))
else:
print('error')
self.server.newConnection.connect(self.onNewConnection)
print(self.server.isListening())
def onNewConnection(self):
self.clientConnection = self.server.nextPendingConnection()
self.clientConnection.textMessageReceived.connect(self.processTextMessage)
self.clientConnection.binaryMessageReceived.connect(self.processBinaryMessage)
self.clientConnection.disconnected.connect(self.socketDisconnected)
self.clients.append(self.clientConnection)
def processTextMessage(self, message):
if (self.clientConnection):
self.clientConnection.sendTextMessage(message)
def processBinaryMessage(self, message):
if (self.clientConnection):
self.clientConnection.sendBinaryMessage(message)
def socketDisconnected(self):
if (self.clientConnection):
self.clients.remove(self.clientConnection)
self.clientConnection.deleteLater()
if __name__ == '__main__':
import sys
app = QtWidgets.QApplication(sys.argv)
serverObject = QtWebSockets.QWebSocketServer('My Socket', QtWebSockets.QWebSocketServer.NonSecureMode)
server = MyServer(serverObject)
serverObject.closed.connect(app.quit)
app.exec_()
我需要在 pyqt5 中创建一个 websocket 服务器,请阅读 5.3 版本的文档,其中包含所有必需的类,请按照 C ++ 中的这些示例 http://doc.qt.io/qt-5/qtwebsockets-examples.html 这是结果:
from PyQt5 import QtCore, QtWebSockets, QtNetwork
class MyServer(QtCore.QObject):
def __init__(self, parent=None):
super(QtCore.QObject, self).__init__(parent)
self.server = QtWebSockets.QWebSocketServer('My Socket', QtWebSockets.QWebSocketServer.NonSecureMode)
if self.server.listen(QtNetwork.QHostAddress.LocalHost, 1302):
print('Connected: '+self.server.serverName()+' : '+self.server.serverAddress().toString()+':'+str(self.server.serverPort()))
else:
print('error')
self.server.newConnection.connect(self.onNewConnection)
print(self.server.isListening())
def onNewConnection(self):
print(self.sender())
print("inside")
self.server.textMessageReceived.connect(self.processTextMessage)
self.server.binaryMessageReceived.connect(self.processBinaryMessage)
self.server.disconnected.connect(self.socketDisconnected)
def processTextMessage(self, message):
print(message)
def processBinaryMessage(self, message):
print(message)
def socketDisconnected(self):
print('out')
if __name__ == "__main__":
import sys
app = QtWidgets.QApplication(sys.argv)
MyServer()
sys.exit(app.exec_())
当运行 isListening 方法时,returns 正确,这让我相信这段代码是正确的,但是我尝试通过 javascript 客户端(html5 websocket)连接并且它 returns 我是服务器连接错误,当我尝试通过 telnet (telnet localhost 1302) 拍摄服务器时也会发生同样的情况。
实际上信号有问题:您不必连接服务器,但需要连接 clientConnections:
def onNewConnection(self):
clientConnection = self.server.nextPendingConnection()
clientConnection.disconnected.connect(clientConnection.deleteLater)
print(self.sender())
print("inside")
clientConnection.textMessageReceived.connect(self.processTextMessage)
clientConnection.binaryMessageReceived.connect(self.processBinaryMessage)
self.server.disconnected.connect(self.socketDisconnected)
然后我尝试使用 html5 客户端:
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
<title>WebSocket Test</title>
<script>
//var wsUri = "ws://echo.websocket.org/";
var wsUri = "ws://127.0.0.1:1302";
var output;
function init() { output = document.getElementById("output"); testWebSocket(); }
function testWebSocket() {
websocket = new WebSocket(wsUri);
websocket.onopen = function(evt) { onOpen(evt) };
websocket.onclose = function(evt) { onClose(evt) };
websocket.onmessage = function(evt) { onMessage(evt) };
websocket.onerror = function(evt) { onError(evt) }; }
function onOpen(evt) { writeToScreen("CONNECTED"); doSend("WebSocket rocks"); }
function onClose(evt) { writeToScreen("DISCONNECTED"); }
function onMessage(evt) {
writeToScreen('<span style="color: blue;">RESPONSE: ' + evt.data+'</span>'); websocket.close();
}
function onError(evt) { writeToScreen('<span style="color: red;">ERROR:</span> ' + evt.data); }
function doSend(message) {
writeToScreen("SENT: " + message); websocket.send(message);
}
function writeToScreen(message) {
var pre = document.createElement("p");
pre.style.wordWrap = "break-word";
pre.innerHTML = message;
output.appendChild(pre); }
window.addEventListener("load", init, false);
</script>
</head>
<body>
<h2>WebSocket Test</h2>
<div id="output"></div>
</body>
</html>
然后我们至少在服务器端连接和打印客户端消息"WebSocket rocks"。但是代码还有待完善
感谢回复,代码中还有其他错误,如果有人需要,最后的代码:
from PyQt5 import QtCore, QtWebSockets, QtNetwork, QtWidgets
class MyServer(QtCore.QObject):
def __init__(self, parent):
super(QtCore.QObject, self).__init__(parent)
self.clients = []
self.server = QtWebSockets.QWebSocketServer(parent.serverName(), parent.secureMode(), parent)
if self.server.listen(QtNetwork.QHostAddress.LocalHost, 1302):
print('Connected: '+self.server.serverName()+' : '+self.server.serverAddress().toString()+':'+str(self.server.serverPort()))
else:
print('error')
self.server.newConnection.connect(self.onNewConnection)
print(self.server.isListening())
def onNewConnection(self):
self.clientConnection = self.server.nextPendingConnection()
self.clientConnection.textMessageReceived.connect(self.processTextMessage)
self.clientConnection.binaryMessageReceived.connect(self.processBinaryMessage)
self.clientConnection.disconnected.connect(self.socketDisconnected)
self.clients.append(self.clientConnection)
def processTextMessage(self, message):
if (self.clientConnection):
self.clientConnection.sendTextMessage(message)
def processBinaryMessage(self, message):
if (self.clientConnection):
self.clientConnection.sendBinaryMessage(message)
def socketDisconnected(self):
if (self.clientConnection):
self.clients.remove(self.clientConnection)
self.clientConnection.deleteLater()
if __name__ == '__main__':
import sys
app = QtWidgets.QApplication(sys.argv)
serverObject = QtWebSockets.QWebSocketServer('My Socket', QtWebSockets.QWebSocketServer.NonSecureMode)
server = MyServer(serverObject)
serverObject.closed.connect(app.quit)
app.exec_()