尝试使用 socketserver 和端口发送和解码整数时,我收到以下错误ValueError: invalid literal for int() with base 10: ''
(最后是完整的堆栈跟踪)。我在客户端中标记了错误所在的位置#<-----
。请注意,我已经尝试了以下所有方法:增加缓冲区大小,将其作为字符串发送,尝试我能想到的每个种姓(先字符串然后 int,浮动,在发送之前先到 int,先到字节然后再到 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: ''