我正在做一个简单的程序,允许WebSocket数据包,例如登录或发送消息。我创建了几个检查来检查正在发送的数据包。我这样做是为了它会列出正在发送的数据包,如果有未知数据包则关闭程序。我遇到了这个问题,当没有消息被发送时它会调用
onMessage
。登录后它工作正常,但在向服务器发送用户消息后,它会收到某种奇怪的数据包。我在下面链接了服务器和客户端代码。在此先感谢您的帮助。
服务器代码:
from autobahn.twisted.websocket import WebSocketServerProtocol, WebSocketServerFactory
from twisted.internet import reactor
class ServerProtocol(WebSocketServerProtocol):
def __init__(self):
super().__init__()
self.logged_in = False
# Define the message routing table
self.message_routes = {
'LOGIN': self.handleLogin,
'SEND_MESSAGE': self.handleSendMessage,
# Add more message types and corresponding handlers here
}
def onConnect(self, request):
print("Client connected: {0}".format(request.peer))
def onOpen(self):
print("WebSocket connection open.")
def onMessage(self, payload, isBinary):
if isBinary:
print("Binary message received: {0} bytes".format(len(payload)))
else:
message = payload.decode('utf8')
print(message)
message_type, *args = message.split(' ')
if message_type in self.message_routes:
handler = self.message_routes[message_type]
handler(*args)
else:
self.sendMessage("UNKNOWN_MESSAGE_TYPE".encode('utf8'))
def onClose(self, wasClean, code, reason):
print("WebSocket connection closed: {0}".format(reason))
self.logged_in = False
def checkCredentials(self, username, password):
# Your credential checking logic here
# Return True if the credentials are valid, False otherwise
return True if (username, password) == ('username', 'password') else False
def handleLogin(self, username, password):
if self.checkCredentials(username, password):
self.logged_in = True
self.sendMessage("LOGIN_SUCCESS".encode('utf8'))
print("Successful login from {0}".format(self.peer))
else:
self.sendMessage("LOGIN_FAILURE".encode('utf8'))
def handleSendMessage(self, message):
if self.logged_in:
print("Text message received from {0}: {1}".format(self.peer, message))
else:
self.sendMessage("NOT_LOGGED_IN".encode('utf8'))
if __name__ == '__main__':
factory = WebSocketServerFactory()
factory.protocol = ServerProtocol
reactor.listenTCP(9000, factory)
print("MESSAGE: Server successfully started.")
reactor. run()
客户代码:
from autobahn.twisted.websocket import WebSocketClientProtocol, WebSocketClientFactory
from twisted.internet import reactor
class MyClientProtocol(WebSocketClientProtocol):
def onOpen(self):
print("Connection opened.")
# Send the login message to the server
username = input("Enter your username: ")
password = input("Enter your password: ")
login_message = f"LOGIN {username} {password}"
self.sendMessage(login_message.encode('utf-8'))
def onMessage(self, payload, isBinary):
print("Message received from server: {}".format(payload.decode('utf8')))
if not isBinary and payload is not None:
message = payload.decode('utf-8')
if message == "LOGIN_SUCCESS":
print("Login successful!")
# Send the text message to the server
text_message = input("Enter your message: ")
message = f"SEND_MESSAGE {text_message}"
self.sendMessage(message.encode('utf-8'))
if message == "LOGIN_FAILURE":
print("Login failed. Check your username and password.")
if message == "NOT_LOGGED_IN":
print("Not logged in. Unable to send messages.")
if message == "UNKNOWN_MESSAGE_TYPE":
print("Packet UNKNOWN_MESSAGE_TYPE was sent. Please fix the code bro")
else:
print("Unknown packet! Closing connection")
self.sendClose(code=1000, reason="Client {0} disconnected cleanly.".format(self.peer))
self.transport.loseConnection()
else:
print("Received binary message.")
def onClose(self, wasClean, code, reason):
print("Connection closed.")
if __name__ == '__main__':
# Set up the client factory and connect to the server
factory = WebSocketClientFactory("ws://localhost:8080")
factory.protocol = MyClientProtocol
reactor.connectTCP("localhost", 9000, factory)
reactor.run()