首页 > 解决方案 > 我的 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()

标签: python-3.xsocketssocketserverpython-sockets

解决方案


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只会返回定的字节数。它也可能返回更少。


推荐阅读