I'm trying to learn pyraknet so I can incorporate it in a simple LAN
game. Starting with the basics, (1) I want to send a single string
from client to server. Then (2) send
complex data ( ie: location coordinates + name ) to server.
I was reading the previous post 'sending strings'. Using its code,
plus
looking at the official demo plus nibbler code. But, I can't get this
program to work.
1) How do you save the connection info properly? Using another
language, I
would have saved the host address ( or socket handle) for use with
later
.send() calls. So on .connect I thought I could save the playerID for
later
calls.
But can't figure out how to do this. The documentation is almost none,
so I
cannot figure it out.
2) How do I fix my code?
# send_string.py
VERSION = "0.0.3"
WINDOW_TITLE = "pyraknet : send string v%s" % (VERSION)
try:
import os,sys
import pygame
from pygame.locals import *
# import jakelib
# from jakelib.text import Text, FPSText
from optparse import OptionParser
import time
import struct
import pyraknet
from pyraknet import PacketTypes, PacketReliability,
PacketPriority
except ImportError, err:
print "Couldn't load module. %s" % (err)
sys.exit(2)
class PeerBase():
def __init__(self): self.done = True
def update(self):
p = self.net.receive()
if p: self.handle_packet(p)
def loop(self):
while not self.done:
time.sleep(.5)
p = self.net.receive()
if p: self.handle_packet(p)
def decodeMessage(self, p):
"""returns the string that is the message"""
ret = ""
for c in packet.data[1:]: # cut pyraknet flag
ret += chr(ord(c))
return ret[:-1] # cut null terminator
def send(self, message, address):
"""send string to addr"""
msg = struct.pack('B', PacketTypes.ID_USER_PACKET_ENUM)
+message
self.net.send(msg, len(msg), PacketPriority.MEDIUM_PRIORITY,
PacketReliability.RELIABLE, 0, address )
class Client(PeerBase):
def __init__(self):
PeerBase.__init__(self)
self.net = pyraknet.Peer()
self.net.init(thread_sleep_timer=30)
self.net.connect('localhost', 5555)
self.done = False
print 'Connecting to server'
def do_msg(self, msg):
print "sending: ", msg
# use default ID? ( from nibble )
self.send( msg, 0)
# else he does this, not sure exactly what?
# self.send( msg, pyraknet.PlayerAddress() )
self.done = True # quit as soon as message is sent
def handle_packet(self, p):
ptype = ord(p.data[0])
if ptype == PacketTypes.ID_CONNECTION_ATTEMPT_FAILED:
print 'Could not connect, quitting...'
self.done = True
elif ptype == PacketTypes.ID_CONNECTION_REQUEST_ACCEPTED:
print 'connected to server!'
elif ptype == PacketTypes.ID_USER_PACKET_ENUM:
print 'server told me to quit. quitting.'
self.done = True
class Server(PeerBase):
def __init__(self, game):
PeerBase.__init__(self)
self.game = game
self.net = pyraknet.Peer()
self.net.init(peers=10, port=5555, thread_sleep_timer=30)
self.net.set_max_connections(10)
self.done = False
print 'Waiting for connection...'
def handle_packet(self, p):
pdata = ord(p.data[0])
if pdata == PacketTypes.ID_NEW_INCOMING_CONNECTION:
print 'a client just connected. sending a quit order'
data = struct.pack('B', PacketTypes.ID_USER_PACKET_ENUM)
self.net.send(data, len(data),
PacketPriority.MEDIUM_PRIORITY,
PacketReliability.RELIABLE, 0, p.address)
elif pdata == PacketTypes.ID_USER_PACKET_ENUM:
print 'Got: ', packet.data[1:], ' from: ',
self.net.get_address_string(p.address)
class ClientNetMain():
def __init__(self):
self.net = Client()
def do_msg(self,msg): self.net.do_msg(msg)
def main_loop(self):
self.net.loop()
class ServerNetMain():
"""."""
done = False
elapsed = 0
now =0
last = 0
def __init__(self, width=640, height=480):
"""Initialize PyGame"""
pygame.init()
self.width, self.height = width, height
self.screen = pygame.display.set_mode(( self.width,
self.height ))
pygame.display.set_caption( WINDOW_TITLE )
self.clock = pygame.time.Clock()
self.bLimitFPS = True
self.fps_limit = 30
self.net = Server(self)
self.next_round()
def next_round(self, round=0): pass
def main_loop(self):
"""Game() main loop"""
while not self.done:
self.handle_events()
self.update()
self.draw()
self.update_net()
# delay here: toggle FPS cap
if self.bLimitFPS: self.clock.tick( self.fps_limit )
else: self.clock.tick()
def handle_events(self):
"""do events."""
events = pygame.event.get()
for event in events:
if event.type == pygame.QUIT: sys.exit()
elif event.type == KEYDOWN: # exit on ESC
if (event.key == K_ESCAPE): self.done = True
def update_net(self): self.net.update()
def update(self):
self.last = self.now
self.now = pygame.time.get_ticks()
self.elapsed = (self.now - self.last) / 1000.
def draw(self):
self.screen.fill( (0,0,0))
pygame.display.flip()
def do_server(host,port):
print "== server =="
game = ServerNetMain()
game.main_loop()
def do_client(host,port,msg):
print "== client =="
game = ClientNetMain()
game.do_msg(msg)
game.main_loop()
if __name__ == '__main__':
# command args:
p = OptionParser(version=VERSION)
p.add_option("-c", action='store_false', dest="client",
default=True,
help="run client")
p.add_option("-s", action='store_true', dest="server",
default=False,
help="run server")
p.add_option("--host", dest="host", default='127.0.0.1',
help="host")
p.add_option("-p", dest="port", default='1234', help="port")
p.add_option("-m", dest="msg", default='', help="message to send")
(o,args) = p.parse_args()
if o.server: do_server(o.host,o.port)
else: do_client(o.host,o.port,o.msg)
thanks,
--
Jake