gpt4 book ai didi

python - 从服务器获取响应

转载 作者:行者123 更新时间:2023-12-01 07:22:41 26 4
gpt4 key购买 nike

我正在尝试制作一个服务器-客户端程序,其中服务器将监听客户端消息并依赖于该消息,将回复。我从 client 发送一 strip 有 usernamecontent 的消息,server 接受它并打印一条消息发送到 client 直到这里一切都很好。但是当发送消息时服务器会抛出错误:

 `TypeError: byte indices must be integers or slices, not str`

看起来这行是问题所在,但我不确定......

`clientsocket.send(msg['header'] + msg['data'])`

这是完整的服务器代码。如果还需要客户端代码,请告诉我。

import socket
import time
import pickle
import select

HEADERSIZE = 10
IP = "127.0.0.1"
PORT = 1234


s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
s.bind((IP, PORT))
s.listen()
sockets_list = [s]
clients = {}

# Handles message receiving
def receive_message(clientsocket):
try:
message_header = clientsocket.recv(HEADERSIZE)
if not len(message_header):
return False

message_length = int(message_header.decode('utf-8').strip())
return {'header': message_header, 'data': clientsocket.recv(message_length)}

except:
return False


while True:
read_sockets, _, exception_socket = select.select(sockets_list, [], sockets_list)
for notified_socket in read_sockets:
if notified_socket == s:
clientsocket, address = s.accept()
user = receive_message(clientsocket)
if user is False:
continue

sockets_list.append(clientsocket)
clients[clientsocket] = user

print(f"Connection from {address[0]}:{address[1]} has been estabilished! User:{user['data'].decode('utf-8')}")


else:
message = receive_message(notified_socket)

if message is False:
print(f"Close connection from {clients[notified_socket]['data'].decode('utf-8')}")
sockets_list.remove(notified_socket)
del clients[notified_socket]
continue

user = clients[notified_socket]
#message_decoded = message['data'].decode('utf-8')
print(f'Received message from {user["data"].decode("utf-8")}: {message["data"].decode("utf-8")}')

for clientsocket in clients:
if clientsocket == notified_socket:
if message["data"].decode("utf-8") == "y":
#d = {1: "Hey", 2: "there"}

msg = pickle.dumps("th.jpeg")
print(msg)

msg = bytes(f'{len(msg):<{HEADERSIZE}}', "utf-8") + msg
clientsocket.send(msg['header'] + msg['data'])

else:
d = {1: "Hey", 2: "there"}
msg = pickle.dumps(d)
print(msg)
# msg = bytes(f'{len(msg):<{HEADERSIZE}}', "utf-8") + msg
clientsocket.send(msg['header'] + msg['data'])

for notified_socket in exception_socket:
sockets_list.remove(notified_socket)
del clients[notified_socket]

这里是完整的错误代码:

Connection from 127.0.0.1:48480 has been estabilished! User:j
Received message from j: y
b'\x80\x03X\x07\x00\x00\x00th.jpegq\x00.'
Traceback (most recent call last):
File "server.py", line 69, in <module>
clientsocket.send(msg['header'] + msg['data'])
TypeError: byte indices must be integers or slices, not str

如您所见,它一直有效直到发送消息行

最佳答案

msg = pickle.dumps("th.jpeg")将编码字符串 "th.jpeg"作为字节对象。 msg = bytes(f'{len(msg):<{HEADERSIZE}}', "utf-8") + msg只是将该字节对象添加到另一个字节对象中。

所以msg是一个简单的字节对象,而不是任何类型的服务器数据包或类似的数据包。因此无法订阅msgmsg['header']或任何其他字符串。

你的代码看起来有点奇怪,但也许试试这一行:

clientsocket.send(msg)

由于您已经在转换 msg对于bytes-object,可以直接发送给客户端。您只需在客户端中对其进行正确解码即可。

关于python - 从服务器获取响应,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57622591/

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