gpt4 book ai didi

python - 无法通过套接字服务器发送整数

转载 作者:太空宇宙 更新时间:2023-11-04 10:46:19 25 4
gpt4 key购买 nike

尝试使用套接字服务器和端口发送和解码整数时,出现以下错误 ValueError: invalid literal for int() with base 10: '' (最后的完整堆栈跟踪)。我用#<-----标记了错误的地方。在客户端。请注意,我已经尝试了以下所有方法:增加缓冲区大小,将其作为字符串发送,尝试我能想到的每一种种姓(首先是字符串,然后是 int,然后是 float,然后是 int,然后再发送,然后是 byte,然后是 int,等)虽然我可能错过了一个。

这是我的服务器的代码:

import socketserver
import threading
import gameplayer


class GameServer:
class GameServerUDPHandler(socketserver.BaseRequestHandler):
def handle_register(self, socket, client_address):
number = len(self.server.base.players) # Zero based
number = number + 1 # One based
socket.sendto(bytes(number), client_address)
self.server.base.players[number] = gameplayer.GamePlayer(id=number)
print(self.server.base.players)

def handle(self):
data = self.request[0].strip()
data = str(data, 'utf-8')
print(data)
socket = self.request[1]
data = data.split('\n')
option = data[0]
print(option)
c_add = self.client_address
if option == "register":
self.handle_register(socket, c_add)
print("test")
elif option == "get_postion":
handle_get_postion(socket, c_add, data[1])
elif option == "change_postion":
hande_changed_postion(socket, c_add, data[1])
# print("{} wrote:".format(self.client_address[0]))
# socket.sendto(data.upper(), self.client_address)

def __init__(self, port):
self.server = socketserver.UDPServer(("localhost", port), self.GameServerUDPHandler)
self.server.base = self
self.players = {}

def start_server(self):
threading.Thread(target=self.server.serve_forever).start()

我的客户(错误所在):

class GameClient:
def __init__(self, port, host):
self.port = port
self.host = host
self.socket = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)

def register(self):
self.socket.sendto(bytes("register\n", "utf-8"), (self.host, self.port))
self.numberID = int(self.socket.recv(10240).strip()) #<- WHERE ISSUE IS
print("Received: {}".format(self.numberID))

完整输出(错误从标记部分开始):

register
register
{1: <gameplayer.GamePlayer object at 0x10078e390>}
test
Traceback (most recent call last): #<---- Where the error starts in the output.
File "main.py", line 8, in <module>
client.register()
File "/Users/Mike/Desktop/Main/Programming/Work Space/Python/Game/gameclient.py", line 12, in register
self.numberID = int(self.socket.recv(10240))
ValueError: invalid literal for int() with base 10: ''

最佳答案

更改服务器代码中的以下行:

socket.sendto(bytes(number), client_address)

与:

socket.sendto(str(number).encode('utf-8'), client_address)

>>> bytes(3)
b'\x00\x00\x00'
>>> str(3)
'3'
>>> str(3).encode('utf')
b'3'

以及回溯的原因

>>> int(bytes(3))
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
ValueError: invalid literal for int() with base 10: ''

关于python - 无法通过套接字服务器发送整数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17035697/

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