• Stars
    star
    165
  • Rank 228,834 (Top 5 %)
  • Language
    Python
  • License
    GNU Lesser Genera...
  • Created almost 10 years ago
  • Updated almost 2 years ago

Reviews

There are no reviews yet. Be the first to send feedback to the community and the maintainers!

Repository Details

Lightweight multiplayer network library for python games

Note: this project uses deprecated libraries (#46) and isn't actively maintained any more.

PodSixNet - lightweight multiplayer networking library for Python games

PodSixNet is a lightweight network layer designed to make it easy to write multiplayer games in Python. It uses Python's built in asyncore library and rencode.py (included) to asynchronously serialise network events and arbitrary data structures, and deliver them to your high level classes through simple callback methods.

Each class within your game client which wants to receive network events, subclasses the ConnectionListener class and then implements Network_* methods to catch specific user-defined events from the server. You don't have to wait for buffers to fill, or check sockets for waiting data or anything like that, just do connection.Pump() once per game loop and the library will handle everything else for you, passing off events to all classes that are listening. Sending data back to the server is just as easy, using connection.Send(mydata). Likewise on the server side, events are propagated to Network_* method callbacks and data is sent back to clients with the client.Send(mydata) method.

The PodSixNet mailing list is good for getting help from other users.

For users of the Construct game making environment for Windows, there is a tutorial on doing multiplayer networking with PodSixNet, here. Thanks to Dave Chabo for contributing this tutorial.

Here is another tutorial by Julian Meyer.

Install

pip install PodSixNet

or

easy_install PodSixNet

From source

First make sure you have Python 2.4 or greater installed (python 3 also works).

Next you'll want to get the PodSixNet source.

The module is found inside a subdirectory called PodSixNet within the top level folder. There's an __init__.py inside there, so you can just copy or symlink the PodSixNet sub-directory into your own project and then do import PodSixNet, or else you can run sudo python setup.py install to install PodSixNet into your Python path. Use sudo python setup.py develop if you want to stay up to date with the cutting edge and still be able to svn/bzr up every now and then.

By default PodSixNet uses a binary encoder to transfer data over the network, but it can optionally use the JSON format or other formats supported by a serialiser which has 'dumps' and 'loads' methods. If you want to serialise your data using JSON you can change the first line of Channel.py to 'from simplejson import dumps, loads' or use the built-in json library in Python 2.6 or higher. This will allow you to write game clients in languages that can't read the 'rencode' binary format, such as Javascript.

Examples

Chat example:

  • python examples/ChatServer.py
  • and a couple of instances of python examples/ChatClient.py

Whiteboard example:

  • python examples/WhiteboardServer.py
  • and a couple of instances of python examples/WhiteboardClient.py

LagTime example (measures round-trip time from the server to the client):

  • python examples/LagTimeServer.py
  • and a couple of instances of python examples/LagTimeClient.py

Quick start - Server

You will need to subclass two classes in order to make your own server. Each time a client connects, a new Channel based class will be created, so you should subclass Channel to make your own server-representation-of-a-client class like this:

from PodSixNet.Channel import Channel

class ClientChannel(Channel):

    def Network(self, data):
        print data

    def Network_myaction(self, data):
        print "myaction:", data

Whenever the client does connection.Send(mydata), the Network() method will be called. The method Network_myaction() will only be called if your data has a key called 'action' with a value of "myaction". In other words if it looks something like this:

data = {"action": "myaction", "blah": 123, ... }

Next you need to subclass the Server class like this:

    from PodSixNet.Server import Server
    
    class MyServer(Server):
        
        channelClass = ClientChannel
        
        def Connected(self, channel, addr):
            print 'new connection:', channel

Set channelClass to the channel class that you created above. The method Connected() will be called whenever a new client connects to your server. See the example servers for an idea of what you might do each time a client connects. You need to call Server.Pump() every now and then, probably once per game loop. For example:

    myserver = MyServer()
    while True:
        myserver.Pump()
        sleep(0.0001)

When you want to send data to a specific client/channel, use the Send method of the Channel class:

channel.Send({"action": "hello", "message": "hello client!"})

Quick start - Client

To have a client connect to your new server, you should use the Connection module. See pydoc Connection for more details, but here's a summary:

Connection.connection is a singleton Channel which connects to the server. You'll only have one of these in your game code, and you'll use it to connect to the server and send messages to the server.

from PodSixNet.Connection import connection

# connect to the server - optionally pass hostname and port like: ("mccormick.cx", 31425)
connection.Connect()

connection.Send({"action": "myaction", "blah": 123, "things": [3, 4, 3, 4, 7]})

You'll also need to put the following code once somewhere in your game loop:

connection.Pump()

Any time you have an object in your game which you want to receive messages from the server, subclass ConnectionListener. For example:

    from PodSixNet.Connection import ConnectionListener
    
    class MyNetworkListener(ConnectionListener):
    
        def Network(self, data):
            print 'network data:', data
        
        def Network_connected(self, data):
            print "connected to the server"
        
        def Network_error(self, data):
            print "error:", data['error'][1]
        
        def Network_disconnected(self, data):
            print "disconnected from the server"
        
        def Network_myaction(data):
            print "myaction:", data

Just like in the server case, the network events are received by Network_* callback methods, where you should replace '*' with the value in the 'action' key you want to catch. You can implement as many or as few of the above as you like. For example, NetworkGUI would probably only want to listen for the _connected, _disconnected, and _error network events. The data for _error always comes in the form of network exceptions, like (111, 'Connection refused') - these are passed straight from the socket layer and are standard socket errors.

Another class might implement custom methods like Network_myaction(), which will receive any data that gets sent from the server with an 'action' key that has the name 'myaction'. For example, the server might send a message with the number of players currently connected like so:

channel.Send({"action": "numplayers", "players": 10})

And the listener would look like this:

    from PodSixNet.Connection import ConnectionListener
    
    class MyPlayerListener(ConnectionListener):
    
        def Network_numplayers(data):
            # update gui element displaying the number of currently connected players
            print data['players']

You can subclass ConnectionListener as many times as you like in your application, and every class you make which subclasses it will receive the network events via named Network callbacks. You should call the Pump() method on each object you instantiate once per game loop:

    gui = MyPlayerListener()
    while 1:
        connection.Pump()
        gui.Pump()

License

Copyright Chris McCormick, 2009-2015.

PodSixNet is licensed under the terms of the LGPL v3.0 or higher. See the file called COPYING for details.

This basically means that you can use it in most types of projects (commercial or otherwise), but if you make changes to the PodSixNet code you must make the modified code available with the distribution of your software. Hopefully you'll tell us about it so we can incorporate your changes. I am not a lawyer, so please read the license carefully to understand your rights with respect to this code.

Why not use Twisted instead?

Twisted is a fantastic library for writing robust network code. I have used it in several projects in the past, and it was quite nice to work with. That said, Twisted:

  • wants to steal the mainloop
  • is bloated not KISS (it implements many many different protocols)
  • has a weird template launching language when Python should do just fine
  • is not written 100% for the specfic use-case of multiplayer games

These are some of the reasons why I decided to write a library that is lightweight, has no dependencies except Python, and is dedicated 100% to the task of multiplayer game networking.

More Repositories

1

DoodleCSS

A simple hand drawn HTML/CSS theme
HTML
1,049
star
2

bugout

Back end web app services over WebRTC.
JavaScript
614
star
3

flk

A LISP that runs wherever Bash is
Shell
498
star
4

slingcode

personal computing platform
Clojure
410
star
5

sitefox

Node + cljs backend web framework
Clojure
290
star
6

awesome-clojure-likes

Curated list of Clojure-like programming languages.
184
star
7

rogule.com

A dungeon a day keeps the Balrog away
JavaScript
177
star
8

gitnonymous

Make pseudonymous Git commits over Tor
Shell
176
star
9

motionless

Generate static sites with code.
JavaScript
78
star
10

dirc

p2p IRC-inspired self-hosted web chat.
Clojure
77
star
11

blender-hylang-live-code

Live-coding Blender with Hy(lang)
Hy
69
star
12

jsGameSoup

Make games with Javascript.
JavaScript
66
star
13

roguelike-browser-boilerplate

A boilerplate for browser based Roguelike game development
JavaScript
62
star
14

PdDroidParty

Run Pure Data DSP patches on Android - native GUIs emulated.
Java
62
star
15

minimal-stylesheet

CSS to get a web app up and running
HTML
60
star
16

twiiit.com

A redirecting proxy for Nitter
JavaScript
55
star
17

build-decentralized-web-app

Build a decentralized web chat in 15 minutes
HTML
52
star
18

SyncJams

Network-synchronised metronome and state dictionary for music applications.
Pure Data
45
star
19

pd-ws

Websocket communication for Pure Data.
HTML
43
star
20

svg-flipbook

SVG flipbook animation with layers
Clojure
40
star
21

speccy

eight-bit algorave livecoding in clojurescript
Clojure
39
star
22

dreamtime

Peer-to-peer for shell scripts.
JavaScript
38
star
23

aish

Shell script one-liners right in your terminal prompt
Shell
23
star
24

webrtc-signaling-mesh

Decentralized signaling for WebRTC
Clojure
23
star
25

tweetfeast.com

Twitter sentiment analysis SaaS
JavaScript
23
star
26

ntpl

Manipulate and render HTML in Python
Python
22
star
27

frock

Clojure-flavoured PHP
PHP
22
star
28

aSid

Moog-like synth for Commodore 64
C
16
star
29

catch-all-errors

Catch all JavaScript errors and post them to your server
JavaScript
16
star
30

roguelike-celebration-2021

Talk: Building Juicy Minimal Roguelikes in the Browser
HTML
14
star
31

drillbit

Algorave drill-n-bass-ish music generator.
Hy
13
star
32

livereload.net

Browser live-reloading web dev tool
Clojure
11
star
33

lolPd

Tiny wrist-saving DSL for Pure Data.
Pure Data
11
star
34

pd-acid-core

303-style acid instrument for Pure Data.
11
star
35

PocketSync

App to sync pocket operator devices
HTML
11
star
36

media-remote

Reverse engineered S*ny "Android Media Remote" for nodejs
JavaScript
11
star
37

makesprite

Make game sprites with image generators
Clojure
11
star
38

create-sitefox-nbb

Get a ClojureScript + sitefox + nbb server with one command
Clojure
11
star
39

juice-it

CSS game juice animations
CSS
10
star
40

c64core

retrocompute aesthetics twitter bot
Clojure
10
star
41

hexadecimal-die

OpenSCAD script to generate a sixteen sided "spherical cap" style hexadecimal die.
OpenSCAD
10
star
42

ball-smash-dungeon

ball physics roguelike
Clojure
9
star
43

create-shadowfront

Quickly bootstrap ClojureScript + shadow-cljs + Reagent
JavaScript
7
star
44

bitcoin-random-oracle

Use the Bitcoin network as an entropy source.
Python
7
star
45

graphviz-livecoder

Live-code Graphviz
Makefile
7
star
46

sitefox-payments

Stripe subscriptions for Sitefox sites
Clojure
7
star
47

blockhead

A collection of Pure Data abstractions styled after rjlib.
Pure Data
7
star
48

speedy-spa

Fast loading material SPA test in LISP
CSS
7
star
49

algotracker

Algorithmic module tracker generator
JavaScript
6
star
50

motion

svg + react motion graphic experiments
Clojure
6
star
51

jqDeclare

jQuery plugin for React-style declarative UIs.
HTML
6
star
52

pd-algobreaks-core

Pure Data patches for making procedural breakbeats.
Pure Data
6
star
53

autotracker

Ben Russell's autotracker extended
Python
5
star
54

htabuilder

LISP to MS Windows HTA app experiment
JavaScript
5
star
55

marcus

Index and search browser bookmarks from the command line.
Hy
5
star
56

itwriter

Write Impulse Tracker modules with JavaScript
JavaScript
5
star
57

scittle-claude-ai

Prompt Claude AI for ClojureScript & Reagent web app artifacts.
HTML
5
star
58

pocketoperations.com

source code to this website
HTML
4
star
59

bitcoin-notebook

Reproduceable blockchain queries for science.
Python
4
star
60

GarageAcidLab

Pure Data patches and scripts that were used to create the squeakyshoecore records as well as the Android app.
Pure Data
4
star
61

riceprioritization.com

A web app to prioritize your options
Clojure
4
star
62

Infinite8BitPlatformer

User-created-content pixel-aesthetic multiplayer game.
Python
4
star
63

808-thing

Pure Data 808 rc-patches wrapper thing.
Pure Data
4
star
64

pd-net-sync

Utilities for synchronising the timing and data of Pure Data patches on a network.
Pure Data
4
star
65

cljs-ultralight

Utilities for making small ClojureScript UI artifacts
Clojure
4
star
66

michaelsoftproject.com

Simple online Gantt chart planner
JavaScript
4
star
67

pd-midi-guis

Abstractions for doing midi-learn buttons and faders in Pure Data.
Pure Data
3
star
68

sssad

Frank Barknect's sssad (state saving) Pure Data abstractions.
Pure Data
3
star
69

tiny-web-game-engine

Tiny game engine for the web
Clojure
3
star
70

reagent-node-render-demo

Demo of rendering a reagent component from nodejs
Clojure
3
star
71

blender-iso-render-bot

Blender script to render isometric sprites
Python
3
star
72

hexatron

Roguelike rendered minimally in three dimensions
Clojure
3
star
73

gba-gpio-tester

Test the GPIO hardware pins on your GBA.
Makefile
3
star
74

liveloops

Console mode audio looping from decades of yore.
C
3
star
75

MonsterVST

Build VST .dlls on Linux, cross compiled for Windows.
C++
3
star
76

cljs-dopeloop

Webaudio utils for dopeloop.ai
Clojure
3
star
77

bootstrappingthis.com

Landing page generator
JavaScript
3
star
78

weeklybeats-2016

Algorithmic rave music 2016
Hy
3
star
79

fugr

Web based RSS feed reader (stalled)
Python
3
star
80

CanOfBeats-droidparty

Procedural hip hop generator for mobile devices.
Pure Data
3
star
81

castpranker.com

Prank your family with chromecast!
HTML
3
star
82

decentral-utils

JavaScript function utils for web decentralization
JavaScript
3
star
83

php-image-paste-upload

PHP page where you can paste images to upload them
PHP
3
star
84

dorcx

A personal social network built on your email box.
Python
3
star
85

bugout-box

Bugout service manager
Clojure
3
star
86

pinfeed

Full-size Pinterest image feed.
HTML
3
star
87

scrypt-hashcash

Scrypt hashcash implementation for node & browsers.
JavaScript
3
star
88

DoodleRogue

A hand drawn roguelike tileset
Makefile
3
star
89

one-million-or-dead

(game) fear and greed and compound interest
Clojure
2
star
90

s-abstractions

A collection of abstractions for the Pure Data patching language
Python
2
star
91

rss-to-newsletter

Web app to turn your RSS feeds into newsletter posts
JavaScript
2
star
92

clojurescript-threejs-playground

Playing with Clojurescript and Three.js with figwheel in between
Clojure
2
star
93

create-sitefox-shadow-fullstack

Bootstrap a full stack Sitefox + shadow-cljs app
Clojure
2
star
94

HypeFrame

HTML5 game boilerplate WIP
JavaScript
2
star
95

emorogue

Roguelikes with emojis
Clojure
2
star
96

algorave-live-rig

Pure Data rig for live mixing algorave
Pure Data
2
star
97

GarageAcidLab-droidparty

Procedural acid for mobile devices.
Pure Data
2
star
98

pdvst-fx

Collection of PdVST music effects
Pure Data
2
star
99

bugout.network

CSS
2
star
100

gnu-linux-in-tiny-places-plug

Talk: GNU/Linux in tiny places (PLUG)
HTML
2
star