我已经成功地编写了一个 UDP 客户端-服务器聊天应用程序,但是我处理请求和响应的方式很老套,而且可扩展性不强。服务器基本上侦听传入的消息,然后根据消息类型运行一些代码:
if command == "CONN":
# handle new connection from client then send "OK"
if command == "MSG":
# send message to other connected clients
...
我对服务器的设计很满意,但客户端真的很繁琐。
以下是客户端可以从服务器发送的命令示例:
Command Name | Argument | Outcome/Description
------------------------------------------------------------------------------
CONN | username | OK, ERR, or timeout if server isn't running
MSG | message | -
USRS | - | ["username1", "username2"]
QUIT | - | -
并从服务器接收:
USRC | username | new user connected
USRD | username | user disconnected
MSG | username, message | print message from user
SHDW | - | server shut down
基本上,我在构建一个可以处理这些不同的命令和响应集的系统时遇到了麻烦。我知道我有一个状态机,并且可以在我的脑海中概念化一个解决方案,我似乎无法将其转化为:
socket.send("CONN username")
if response == "OK":
# connected to the server ok
if response == "ERR":
# oops, there was a problem of sorts
# otherwise handle timeout
socket.send("USRS")
if response == "":
# no other users connected
else:
# print users
# start main listening loop
while True:
# send typed text as MSG
# handle any messages received from the server on separate thread
对于奇怪的 python-esqe 伪代码,任何帮助表示赞赏和道歉。