Socket Programming

From ESE205 Wiki
Jump to navigation Jump to search

(UDP) Socket Programming (for Python)

Sockets were used to communicate wirelessly between Raspberry Pis. A socket is simply a connection to a WiFi network that a computer can send data over.

Step 1: Determining type of socket

There are two main types of sockets that align with the two main types of data transfer protocols computers use to send data over the Internet. TCP (Transmission Control Protocol) is a connected protocol meaning it initializes all of its connections with a handshake and if a socket never hears back from the address it sent data to, it will simply hang forever. UDP (User Datagram Protocol) is connectionless and simply shoots packets off (potentially into the void) whether another computer is listening or not. Because of this, UDP is less secure than TCP - it's impossible to know whether or not the packet was received on the other end without building some additional infrastructure on top of it yourself. However, this also makes it much faster than TCP, because there are fewer steps required to send information to another computer. UDP packets can also be broadcast to the entire network while TCP packets must be directed to a specific address. Consider these attributes before choosing which protocol to use.

The Pi Car Communication project only used UDP packets so the rest of the tutorial will be specific to this protocol. More information on both types can be found here.

Step 2: Initializing socket

Python comes with a built in socket module. Thus, socket functionality can be accessed simply by typing

import socket

at the top of any script.

To actually initialize the socket, simply create a socket object.

sock = socket.socket(socket.AF_INET,socket.SOCK_DGRAM)

where the SOCK_DGRAM option specifies that this is a UDP socket.

Step 3: Sending data with the socket.

After initializing the socket, it's relatively easy to send data over it. Assuming that the socket has already been initialized as sock, calling sock.send(<message>, (<ip>, <port>)) will send <message> to the IP address <ip> on port <port>. To receive a message, simply call sock.recv(<bytes>) where <bytes> is the maximum packet size in bytes.

TL;DR

Full examples of all of this code can be found on this project's GitHub in /experiments/recv.py and /experiments/send.py. Running send on one computer and recv on another should allow you to type at the prompt on the send computer, then press Enter, and see it appear on the recv computer.