[英]check incoming type of data with socket.recv
I need my program to know if the message from the client is a number, so int or float, or a string.我需要我的程序知道来自客户端的消息是数字,因此是 int 或 float,还是字符串。
Until now, my program look like this:到现在为止,我的程序是这样的:
def handle_client_text(conn, addr):
print(f"[NEW CONNECTION] {addr} connected.")
connected = True
while connected:
msg_lenght = conn.recv(HEADER).decode(FORMAT)
if msg_lenght:
msg_lenght = int(msg_lenght)
msg = conn.recv(msg_lenght).decode(FORMAT)
if msg == DISCONNECT_MESSAGE:
connected = False
conn.close()
print ("disconnecting")
print(f"[{addr}] {msg}")
sleep(0.001)
def start():
server.listen()
print(f"[LISTENING] Server is listening on {SERVER}")
while True:
conn, addr = server.accept()
thread = threading.Thread(target=handle_client_text, args=(conn, addr))
thread.start()
print(f"[ACTIVE CONNECTIONS] {threading.activeCount() - 1}")
I need that it can receive numbers other than strings, and that it acts in a different way if its a number or a string.我需要它可以接收字符串以外的数字,并且如果它是数字或字符串,它会以不同的方式运行。
Every variable that isn't defined here is defined in another part of the code.此处未定义的每个变量都在代码的另一部分中定义。
Data that are coming via socket is in byte form, and it becomes a string when you decode()
it and becomes int or float if you convert it with int()
or float()
respectively.通过套接字传入的数据是字节形式,当你
decode()
时它变成一个字符串,如果你分别用int()
或float()
转换它,它就会变成 int 或 float。
Hence, if you want to have different logic based on its datatype, You should either check for all digits/dots or alphanumeric characters to classify between numeric and string datatypes.因此,如果您想根据其数据类型使用不同的逻辑,您应该检查所有数字/点或字母数字字符以在数字和字符串数据类型之间进行分类。 or, If you may have to treat
"12"
as string instead of int, send data type as meta data from client.或者,如果您可能必须将
"12"
视为字符串而不是 int,请将数据类型作为元数据从客户端发送。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.