[Author Prev][Author Next][Thread Prev][Thread Next][Author Index][Thread Index]
Re: [pygame] Re:[pygame] networking example
Here are the actual scripts:
***BEGIN asynchat_serv.py ***
#!/usr/bin/python
### This is the game server ###
import asynchat
import asyncore
import socket
class GameServer(asyncore.dispatcher):
""" The GameServer (mastermind controlling all)
"""
def __init__(self, port):
asyncore.dispatcher.__init__(self)
# create connection
self.create_socket(socket.AF_INET, socket.SOCK_STREAM)
self.set_reuse_addr()
here = ("", port)
self.bind(here)
self.listen(5)
def handle_accept(self):
# accept a connection and create a chat object to handle it
print "Accepting connection"
GameChat(self, self.accept())
class GameChat(asynchat.async_chat):
""" This is the GameChat class. Collects messages and updates other clients.
"""
def __init__(self, server, (conn, addr)):
asynchat.async_chat.__init__(self, conn)
self.set_terminator('\n')
self.server = server
self.buffer = ''
def collect_incoming_data(self, data):
self.buffer = self.buffer + data
def found_terminator(self):
# handle end of message
data = self.buffer
# clear the buffer
self.buffer = ''
print "Server Received: %s" % (data)
cmd = data[:3]
message = data[4:]
# check for any special commands
if cmd == "HEL":
print "%s said Hello" % message
self.push("Hello %s\n" % message)
def handle_close(self):
print 'Closing'
self.close()
if __name__ == "__main__":
# test the server here
gs = GameServer(5000)
#asyncore.loop() # I think asyncore has a longer timeout
because it takes a long time to kill with ctrl-c
while (1):
asyncore.poll(timeout=.01)
*** END asynchat_serv.py ***
*** BEGIN asynchat_client.py ***
# the client side
import asynchat
import asyncore
import socket
class GameClient(asynchat.async_chat):
""" GameClient class. Connects to the server and sends messages.
"""
def __init__(self, host, port):
asynchat.async_chat.__init__(self)
self.create_socket(socket.AF_INET, socket.SOCK_STREAM)
self.buffer = ""
self.set_terminator("\n")
self.address = (host, port) # address of the server to contact
self.connect(self.address)
self.push("HEL BOB\n\n")
def handle_connect(self):
print "Connection Complete"
def collect_incoming_data(self, data):
self.buffer = self.buffer + data
def found_terminator(self):
data = self.buffer
self.buffer = ""
print "Client received: %s" % (data)
def handle_close(self):
self.close()
if __name__ == "__main__":
gc = GameClient("localhost", 5000)
while (1):
asyncore.poll(timeout=.01)
*** END asynchat_client.py ***
On Tue, Apr 29, 2008 at 6:57 PM, Jake b <ninmonkeys@xxxxxxxxx> wrote:
> Brian: I am getting a 404 not found on both of your links.
>
> --
> Jake
>
--
Brian Davis
intrepidhero@xxxxxxxxx
davis.brianjames@xxxxxxxxx