python-3.x - 我的 if & elif 不适用于套接字(python 3)
问题描述
我试图创建一个从客户端接收命令的服务器并确定客户端编写的命令我使用 if & elif 但是当我运行程序并从客户端编写命令时,只有第一个命令有效(if 上的命令)如果我尝试另一个命令(来自 elif & else)系统只是没有响应(就像她在等待什么)
服务器代码:
import socket
import time
import random as rd
soc = socket.socket()
soc.bind(("127.0.0.1", 7777))
soc.listen(5)
(client_socket, address) = soc.accept()
if(client_socket.recv(4) == b"TIME"):
client_socket.send(time.ctime().encode())
elif(client_socket.recv(4) == b"NAME"):
client_socket.send(b"My name is Test Server!")
elif(client_socket.recv(4) == b"RAND"):
client_socket.send(str(rd.randint(1,10)).encode())
elif(client_socket.recv(4) == b"EXIT"):
client_socket.close()
else:
client_socket.send(b"I don't know what your command means")
soc.close()
客户代码:
import socket
soc = socket.socket()
soc.connect(("127.0.0.1", 7777))
client_command_to_the_server = input("""
These are the options you can request from the server:
TIME --> Get the current time
NAME --> Get the sevrer name
RAND --> Get a Random int
EXIT --> Stop the connect with the server
""").encode()
soc.send(client_command_to_the_server)
print(soc.recv(1024))
soc.close()
解决方案
if(client_socket.recv(4) == b"TIME"):
client_socket.send(time.ctime().encode())
这将检查从服务器接收到的前4 个字节
elif(client_socket.recv(4) == b"NAME"):
client_socket.send(b"My name is Test Server!")
这将检查从服务器接收到的接下来的4 个字节。与您假设的相反,它不会再次检查第一个字节,因为您调用recv
读取更多字节。如果没有更多字节(很可能,因为前 4 个字节已被读取),它将简单地等待。您应该调用一次,然后将结果与各种字符串进行比较,而不是调用recv
每个比较。recv
除此之外:recv
只会返回给定的字节数。它也可能返回更少。
推荐阅读
- android - Firebase Cloud:从文档中检索归档的“expireDate”的所有值
- javascript - Firebase 规则 - 查询中的只读值
- c++ - 如何将单词拆分为字母并将它们放入无序列表/集合中?
- android - 如何在辅助功能服务中的可滚动视图上方添加矩形?
- python - 从两个 2D numpy 数组中提取重叠单元格的方法
- java - 仅 8.2 及更高版本的服务器支持 PSQLException 返回自动生成的密钥
- node.js - 我无法使用 Lambda 对来自 Dynamo DB 的 GET 请求的结果进行数字排序
- jquery - 响应式 iframe 轮播模式?
- android - 如何快速找到哪个 subscribe() 方法没有 onError?
- javascript - 在 typescript 中导入一个尚不存在但将存在于构建目录中的模块