Skip to content

Instantly share code, notes, and snippets.

@only-entertainment
Created February 17, 2012 22:32
Show Gist options
  • Save only-entertainment/1855831 to your computer and use it in GitHub Desktop.
Save only-entertainment/1855831 to your computer and use it in GitHub Desktop.
Async Game Server
import asyncore
import socket
import json
state = {}
class UpdateMsg(object):
def __init__(self, data):
sdata = data.strip().split(' ')
self.player = sdata[0]
self.x = sdata[1]
self.y = sdata[2]
self.z = sdata[3]
self.health = sdata[4]
def __str__(self):
return "Player(" + self.player + ") Health(" + self.health + ") Pos(" + self.x + "," + self.y + "," + self.z + ")"
class UpdateStateHandler(asyncore.dispatcher_with_send):
def handle_read(self):
data = self.recv(8192)
if data:
print "RX: " + str(data)
msg = UpdateMsg(data)
print msg
# Store the game state
state[msg.player] = {'id': msg.player, 'x': msg.x, 'y': msg.y, 'z': msg.z, 'h': msg.health}
print str(json.dumps(state))
# Get all other players states
tx = {}
tx['players'] = []
for key in state.keys():
if key == msg.player:
pass
else:
tx['players'].append(state[key])
# Get the environment state
tx['env'] = {'time': '1'}
# Return the game state
tx = json.dumps(tx)
print "TX: " + str(tx)
self.send(tx)
class GameServer(asyncore.dispatcher):
def __init__(self, host, port):
asyncore.dispatcher.__init__(self)
self.create_socket(socket.AF_INET, socket.SOCK_STREAM)
self.set_reuse_addr()
self.bind((host, port))
self.listen(5)
def handle_accept(self):
pair = self.accept()
if pair is None:
pass
else:
sock, addr = pair
#print 'Incoming connection from %s' % repr(addr)
handler = UpdateStateHandler(sock)
print "Running server..."
server = GameServer('localhost', 8080)
asyncore.loop()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment