Added more modifications to the written enet protocol

This commit is contained in:
Manuel Cortez 2020-05-12 20:02:22 -05:00
parent 8eab859f3e
commit a2706cfd25
2 changed files with 35 additions and 11 deletions

View File

@ -11,15 +11,19 @@ class client(object):
self.peer = self.host.connect(address, channel_limit)
def run(self):
running = True
while running:
self.running = True
while self.running:
event = self.host.service(0)
if event.type == enet.EVENT_TYPE_CONNECT:
print("%s: CONNECT" % event.peer.address)
if hasattr(self, "connected"):
self.connected(event.peer)
elif event.type == enet.EVENT_TYPE_DISCONNECT:
print("%s: DISCONNECT" % event.peer.address)
if hasattr(self, "disconnected"):
self.disconnected(event.peer)
elif event.type == enet.EVENT_TYPE_RECEIVE:
print("%s: IN: %r" % (event.peer.address, event.packet.data))
data = event.packet.data
data_dict = json.loads(data, encoding="utf-8")
self.network(event, data_dict)
time.sleep(0.001)
def send_data(self, channel, data, reliable=True):
@ -30,11 +34,17 @@ class client(object):
else:
flags = enet.PACKET_FLAG_UNSEQUENCED
packet = enet.Packet(data_bytes, flags)
self.peer.send(channel, packet)
print(self.peer.send(channel, packet))
def network(self, event, data):
print(data)
def disconnect(self):
self.peer.disconnect()
def close(self):
self.running = False
def __del__(self):
del self.host
del self.peer

View File

@ -4,8 +4,9 @@ import json
class channel(object):
def __init__(self, peer):
def __init__(self, server, peer):
self.peer = peer
self.server = server
def send_data(self, channel, data, reliable=True):
data_str = json.dumps(data, ensure_ascii=False)
@ -25,14 +26,14 @@ class channel(object):
class server(object):
def __init__(self, host=b"localhost", port=33333, peer_count=10, channel_limit=4, incoming_bandwidth=0, outgoing_bandwidth=0):
def __init__(self, host=b"localhost", port=33333, peer_count=256, channel_limit=4, incoming_bandwidth=0, outgoing_bandwidth=0):
address = enet.Address(host, port)
self.host = enet.Host(address, peer_count, channel_limit, incoming_bandwidth, outgoing_bandwidth)
self.peers = {}
def run(self):
running = True
while running:
self.running = True
while self.running:
event = self.host.service(0)
if event.type == enet.EVENT_TYPE_CONNECT:
self.connected(event.peer)
@ -54,7 +55,7 @@ class server(object):
return channel
def connected(self, peer):
p = channel(peer)
p = channel(self, peer)
self.peers[p] = True
print(len(self.peers))
p.send_data(0, dict(action="connected"), False)
@ -67,5 +68,18 @@ class server(object):
print("%s: DISCONNECT" % peer.address)
break
def send_to_all(self, channel, data, reliable=True):
data_str = json.dumps(data, ensure_ascii=False)
data_bytes = bytes(data_str, "utf-8")
if reliable:
flags = enet.PACKET_FLAG_RELIABLE
else:
flags = enet.PACKET_FLAG_UNSEQUENCED
packet = enet.Packet(data_bytes, flags)
self.host.broadcast(channel, packet)
def close(self):
self.running = False
def __del__(self):
del self.host