Python 3.x 我的假设及;elif不适用于套接字(python 3)

Python 3.x 我的假设及;elif不适用于套接字(python 3),python-3.x,sockets,socketserver,python-sockets,Python 3.x,Sockets,Socketserver,Python Sockets,我试图创建一个从客户端接收命令的服务器 为了识别客户端编写的命令,我使用了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) (clie

我试图创建一个从客户端接收命令的服务器 为了识别客户端编写的命令,我使用了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()
这将检查从服务器接收的第一个4字节

elif(client_socket.recv(4) == b"NAME"):
    client_socket.send(b"My name is Test Server!")
这将检查从服务器接收的下一个4字节。与您假设的相反,它不会再次检查第一个字节,因为您调用了
recv
来读取更多字节。如果没有更多的字节(很可能,因为前4个字节已经被读取),它将只是等待。不要为每次比较调用
recv
,而应调用
recv
一次,然后将结果与各种字符串进行比较

除此之外:
recv
将只返回到给定字节数。它的回报也可能更少

elif(client_socket.recv(4) == b"NAME"):
    client_socket.send(b"My name is Test Server!")