gpt4 book ai didi

Python 套接字、数据和字典

转载 作者:行者123 更新时间:2023-12-01 04:55:32 25 4
gpt4 key购买 nike

因此,我尝试搜索与从客户端收到的数据相匹配的字典,但它永远找不到它。

这是我的服务器端代码:

import socket

irTable = {"a1" : "lamp", "a2" : "tv", "b1" : "lamp2", "b2" : "tv2"}

HOST = socket.gethostname()
PORT = 12345
BUFFER = 1024

s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.bind((HOST, PORT))
s.listen(1)

conn, addr = s.accept()
print('Connection address:', addr)
while 1:
data = str(conn.recv(BUFFER).decode())
if not data: break
print("received data:", data)

for i in irTable:
if data in irTable:
print("Found it!")
else:
print("Hmm... not there!")

conn.close()

和客户端:

import socket

IP = socket.gethostname()
PORT = 12345
BUFFER = 1024

MSG = "a1"

s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.connect((IP, PORT))
s.send(MSG.encode())

s.close()

所以此时客户端只将'a1'作为数据发送到服务器,因此

if data in irTable:

应该是这个意思

if "a1" in irTable:

但它永远不会在表中找到 a1,即使知道它在那里......我得到的只是:

>>>
Connection address: ('192.168.0.2', 58271)
received data: a1
Hmm... not there!
Hmm... not there!
Hmm... not there!
Hmm... not there!

我在这里做错了什么?

谢谢

最佳答案

问题是您在找到数据后没有跳出循环而覆盖了数据。因此数据被分配给a1,再次循环并被分配给任何内容。以下服务器代码将按您的预期工作。

import socket

irTable = {"a1" : "lamp", "a2" : "tv", "b1" : "lamp2", "b2" : "tv2"}

HOST = socket.gethostname()
PORT = 12345
BUFFER = 1024

s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.bind((HOST, PORT))
s.listen(1)

conn, addr = s.accept()
print('Connection address:', addr)
data = None
while not data:
data = str(conn.recv(BUFFER).decode())

for i in irTable:
if data in irTable:
print("Found it!")
else:
print("Hmm... not there!")

conn.close()

使用 while 1 的另一种方法可能是:

while 1:
data = str(conn.recv(BUFFER).decode())
if data:
break

关于Python 套接字、数据和字典,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27494765/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com