Python Socket Examples

A collection of simple Python programs that show off the capabilities of
the socket module.

Because of the nature of socket programming I've used some embedded
devices including a RaspberryPi, an iRacer, and an eLua board.

This was presented at the 2012 Kiwi Pycon in Dunedin, New Zealand.

Much has been used from the Python socket documentation.


To really get an understanding of websockets I wrote a pure Python
websocket server. Developer caveat - it is not a full implementation of

Bluetooth Sockets

To demonstrate Bluetooth Sockets in Python 3.3 I used the iRacer from
sparkfun with:

  • on-board Bluetooth radio
  • RFCOMM Bluetooth...
  • Protocol is dead easy - 0xXY where X is the direction
    and Y is the speed. E.G 0x16: Direction=Forwards, mid-speed.

There was only ONE mention of "bluetooth" on the Python 3.3 socket
docs... so I had to use the source.

Boiled down to creating a Bluetooth controlled iRacer car with something
like this:

    import socket
    import time

    class BluetoothCar:
        def __init__(self, mac_address="00:12:05:XX:XX:XX"):
            self.socket = socket.socket(

            self.socket.connect((mac_address, 1))

        def forwards(self, duration=1.0):
  , duration)

        def drive(self, command, duration):

CAN Sockets

The Controller Area Network is a bus standard designed to
allow microcontrollers and devices to communicate with each other. It
has priority based bus arbitration, reliable deterministic
communication. Used in cars, trucks, wheelchairs... wikipedia
has more info

SocketCAN is a set of open source CAN drivers and a networking stack
contributed by Volkswagen Research to the Linux kernel. Although out of
date, there are some good docs at brown hat on the low level CAN

Raw shows sending CAN messages using a raw can socket and
receiving a filtered selection of them.


Required creating a patch for Python. Found in python_bcm.patch.

IPv6 Sockets

There are much more thorough treatments of normal network sockets out
there, but for completeness I've included examples and that will work


My presentation notes are in which can be turned into
some sort of slideshow with pandoc:

$ pandoc -s --self-contained --webtex -i -t slidy -o presentation.html