我正在编写一个多人游戏,其中服务器生成一个字段,当每个客户端加入游戏时,该字段就会发送给每个客户端。在进入主要游戏功能之前,我需要确保确实已正确接收并处理了该字段。
我了解到,任何检查或等待成员变量状态的操作传统上都会占用可用于更新同步程序中变量值的任何处理时间。但是我不确定为什么不使用异步样式更新值。
我尝试对值- script: |
sudo apt install -qq -y valgrind
valgrind
进行循环测试,使程序在运行主要游戏功能之前休眠一段时间,并操纵底层套接字来阻塞并等待必要的数据已收到。
客户代码
not None
上面的代码导致
class Client(asyncio.Protocol):
"""Client used to send and receive mine_field data and changes."""
@staticmethod
def get_packet_size(packet: bytes) -> bytes:
"""Get the size of the packet in network byte order."""
return struct.pack('!I', len(packet))
def __init__(self, game_mode: Mode = Mode()):
self._mode = game_mode
self.transport: asyncio.Transport = None
self._sock: socket.socket = None
self._buffer: bytes = b''
self._mine_field: MineField = None
super().__init__()
def connection_made(self, transport) -> None:
"""Establish values pertinent to the server connection.
Args:
transport: the TCP connection interface used to send and
read data to and from the server.
"""
self.transport = transport
print(f'Client connected as'
f'{self.transport.get_extra_info("peername")}')
def data_received(self, data: bytes) -> None:
"""Handle data read from the server.
Args:
data (bytes): the data read from the server socket.
"""
self._buffer += data
while len(self._buffer) > 4:
packet_length: int = struct.unpack('!I', self._buffer[:4:])[0]
if len(self._buffer) < 4 + packet_length:
break
self._buffer = self._buffer[4::]
packet: dict = json.loads(self._buffer[:packet_length:].decode())
affected_row: int = -1
affected_col: int = -1
if 'CELLS' in packet:
self._mine_field = MineField.decode(self._buffer[:packet_length:])
print(f'd : {self}\n{self.get_mine_field()}')
self._buffer = self._buffer[packet_length::]
def get_mine_field(self) -> MineField:
return self._mine_field
def run_client():
host = 'localhost' # '192.168.0.10'
port = 8080
loop = asyncio.get_event_loop()
coro = loop.create_connection(Client, host, port)
transport, client = loop.run_until_complete(coro)
print(f'm : {client.get_mine_field()}')
try:
loop.run_forever()
except KeyboardInterrupt:
loop.close()
print('\n=== Keyboard closed client ===\n')
finally:
loop.close()
但是应该导致两者都显示字段的表示形式
m : None
d : 2 # 2 0 1 2 2 2 1 1
3 # 3 1 2 # # 3 # 2
# 2 2 # 3 4 5 # 3 #
1 1 1 1 2 # # 3 4 2
0 0 0 1 3 4 4 # 2 #
0 0 0 1 # # 2 1 2 1
1 1 1 1 2 3 3 3 3 2
1 # 1 0 0 2 # # # #
1 1 1 0 0 3 # 7 6 4
0 0 0 0 0 2 # # # #