Socket Programming (in Python)

Vicente González Ruiz

September 12, 2016

Contents

1 Debugging code
2 A TCP receiver
3 A TCP sender
4 Receiving packed data
5 Sending packed data
6 An iterative TCP server
7 A TCP client
8 A concurrent TCP server
9 Another TCP client (for the concurrent TCP server)
10 Minimal UDP receiver
11 Minimal UDP sender
12 The same end-point can be used for TCP and UDP

1 Debugging code

#!/usr/bin/python 
 
’’’Debug mode is activated’’’ 
 
# See: http://docs.python.org/2/library/constants.html 
 
if __debug__: 
    print ’This␣is␣printed’
#!/usr/bin/python O 
#                  ^ 
#                  | 
# Notice this!+ 
# See: http://docs.python.org/2/library/constants.html 
 
’’’ Debug mode is disabled’’’ 
 
if __debug__: 
    print ’This␣is␣not␣printed’

2 A TCP receiver

#!/usr/bin/python 
’’’A simple TCP receiver’’’ 
 
# See: http://docs.python.org/2/library/socket.html 
 
import socket 
 
listening_adapter = ’’ # Listen to all adapters 
listening_port = 9999 
listening_queue_size = 0 # Only an incomming connection at the same time 
listening_endpoint = (listening_adapter, listening_port) 
 
sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM) 
sock.bind(listening_endpoint) 
 
print ’I␣am’, sock.getsockname(), ’and␣I␣am␣listening␣...’ 
 
sock.listen(listening_queue_size) # This is a blocking command 
connection = sock.accept() # Return the TCP connection 
(sock, sender) = connection # Only one connection in this example, so, 
                            # we can reuse the socket sock 
 
print ’A␣connection␣with’, sender, ’has␣been␣established’ 
 
longest_message_size = 100 
message = sock.recv(longest_message_size) 
# It waits for a TCP segment of any payload length, but as much 100 
# bytes will be copied into the "message" variable. 
 
print ’\’’+message+’\’’, ’is␣received␣from’, sender 
 
sock.close()

3 A TCP sender

#!/usr/bin/python 
 
’’’A simple TCP sender’’’ 
 
# See: http://docs.python.org/2/library/socket.html 
 
import socket 
 
server_endpoint = (’localhost’, 9999) 
 
sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM) 
sock.connect(server_endpoint) 
 
print ’The␣connection␣with’, sock.getpeername(), ’has␣been␣established’ 
 
sock.send(’hola’) 
 
sock.close()

4 Receiving packed data

#!/usr/bin/python 
 
’’’A packed data receiver’’’ 
 
# See: http://docs.python.org/2/library/struct.html 
 
import socket 
import struct 
 
max_message_size = 100 
 
listening_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM) 
listening_socket.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1) 
listening_socket.bind((’’, 9999)) 
listening_socket.listen(1) 
 
serving_socket = listening_socket.accept() 
message = serving_socket[0].recv(max_message_size) 
 
print struct.unpack(’>Bh5sf’, message) 
 
serving_socket[0].close()

5 Sending packed data

#!/usr/bin/python 
 
’’’A packed data sender’’’’ 
 
#␣See:␣http://docs.python.org/2/library/struct.html 
 
import␣socket 
import␣struct 
 
sock␣=␣socket.socket(socket.AF_INET,␣socket.SOCK_STREAM) 
sock.connect((’localhost’,␣9999)) 
 
unsigned_int8␣=␣3 
signed_int16␣=␣2442 
string␣=␣"Hello" 
float32␣=␣3.14 
 
message␣=␣’’ 
message␣+=␣struct.pack(’B’,␣unsigned_int8) 
message␣+=␣struct.pack(’>h’,␣signed_int16) 
message␣+=␣string 
message␣+=␣struct.pack(’>f’,␣float32) 
 
sock.sendall(message) 
 
sock.close()

6 An iterative TCP server

#!/usr/bin/python 
 
’’’An iterative TCP server’’’ 
 
# See: http://wiki.python.org/moin/TcpCommunication 
# See: http://docs.python.org/2/library/socket.html 
 
import socket 
 
sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM) 
if __debug__: 
    # Reuse the port now 
    sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1) 
sock.bind((’’, 9999)) 
print "Waiting␣for␣connections␣..." 
sock.listen(0) 
 
while True: 
 
    connection = sock.accept() 
    message = connection[0].recv(100) 
    print "Received", message, "from", connection[1] 
    connection[0].sendall(message.upper()) 
    connection[0].close()

7 A TCP client

#!/usr/bin/python 
 
’’’A TCP client’’’ 
 
# See: http://wiki.python.org/moin/TcpCommunication 
# See: http://docs.python.org/2/library/socket.html 
 
import socket 
 
sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM) 
sock.connect((’localhost’, 9999)) 
print "I␣am", sock.getsockname() 
 
message = ’hello’ 
 
sock.sendall(message) 
 
print ’Sent’, message, ’and␣received’, sock.recv(len(message)) 
 
sock.close()

8 A concurrent TCP server

#!/usr/bin/python 
 
’’’A concurrent TCP server’’’ 
 
# See: http://docs.python.org/2/library/socket.html 
# See: http://docs.python.org/2/library/struct.html 
# See: http://docs.python.org/2/library/threading.html 
# See: http://code.activestate.com/recipes/578247basicthreadedpythontcpserver 
# See: http://stackoverflow.com/questions/4783735/problemwithmultithreadedpythonappandsocketconnections 
 
import socket 
import struct 
import time 
import threading 
 
value = 0 
 
class ClientHandler(threading.Thread): 
 
    def __init__(self, client): 
        threading.Thread.__init__(self) 
        self.client_sock, self.client_addr = client 
 
    def run(self): 
 
        global value 
 
        while True: 
            value = int(struct.unpack(’>H’, self.client_sock.recv(struct.calcsize(’>H’)))[0]) 
            print "Received", value, 
            time.sleep(1) 
            print "and␣sending", value 
 
            self.client_sock.sendall(struct.pack(’>H’, value)) 
 
sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM) 
sock.bind((’’, 9999)) 
sock.listen(0) 
print "Waiting␣for␣clients␣..." 
 
while True: # Serve forever. 
    client = sock.accept() 
    ClientHandler(client).start()

9 Another TCP client (for the concurrent TCP server)

#!/usr/bin/python 
 
’’’A client for a concurrent server’’’ 
 
# See: http://docs.python.org/2/library/socket.html 
# See: http://wiki.python.org/moin/TcpCommunication 
# See: http://docs.python.org/2/library/random.html 
 
import socket 
import struct 
import random 
 
sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM) 
sock.connect((’localhost’, 9999)) 
 
while True: 
    value = int(255random.random()) 
    sock.sendall(struct.pack(’>H’, value)) 
    print ’Sent’, value, 
    value = struct.unpack(’>H’, sock.recv(struct.calcsize(’>H’)))[0] 
    print ’and␣received’, value

10 Minimal UDP receiver

#!/usr/bin/python 
 
’’’A minimal UDP receiver’’’ 
 
# See: http://wiki.python.org/moin/UdpCommunication 
# See: http://docs.python.org/2/library/socket.html 
 
import socket 
 
sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM) 
sock.bind((’’, 9999)) 
 
(message, sender) = sock.recvfrom(1) 
# The parameter of socket.recvfrom() indicates the number of bytes to 
# be copied from the payload of the received datagram to the variable 
# "message" 
 
print ’\’’+message+’\’’, ’received␣from’, sender 
 
sock.close()

11 Minimal UDP sender

#!/usr/bin/python 
 
’’’A minimal UDP sender’’’ 
 
# See: http://wiki.python.org/moin/UdpCommunication 
# See: http://docs.python.org/2/library/socket.html 
 
import socket 
 
sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM) 
 
sock.sendto(’hola’, (’localhost’, 9999))

12 The same end-point can be used for TCP and UDP

#!/usr/bin/python 
 
’’’Two threads in the same host can use the same endpoint for 
different protocols’’’ 
 
# See: http://docs.python.org/2/library/socket.html 
# See: http://docs.python.org/2/library/struct.html 
# See: http://docs.python.org/2/library/threading.html 
# See: http://code.activestate.com/recipes/578247basicthreadedpythontcpserver 
# See: http://stackoverflow.com/questions/4783735/problemwithmultithreadedpythonappandsocketconnections 
 
import socket 
import struct 
import time 
import threading 
 
value = 0 
 
class TCP_Handler(threading.Thread): 
 
    def __init__(self, client): 
        threading.Thread.__init__(self) 
        self.client_sock, self.client_addr = client 
 
    def run(self): 
 
        global value 
 
        while True: 
            value = int(struct.unpack(’>H’, self.client_sock.recv(struct.calcsize(’>H’)))[0]) 
            print "Received", value, 
            time.sleep(1) 
            print "and␣sending", value 
 
            self.client_sock.sendall(struct.pack(’>H’, value)) 
 
class UDP_Handler(threading.Thread): 
 
    def __init__(self, sock): 
        threading.Thread.__init__(self) 
        self.sock = sock 
 
    def run(self): 
 
        global value 
 
        while True: 
            (message, sender) = self.sock.recvfrom(struct.calcsize(’>H’)) 
            value = int(struct.unpack(’>H’, message)[0]) 
            print "Received", value, 
            time.sleep(1) 
            print "and␣sending", value 
            self.sock.sendto(struct.pack(’>H’, value), sender) 
 
TCP_sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM) 
TCP_sock.bind((’’, 9999)) 
TCP_sock.listen(0) 
print "Waiting␣for␣TCP␣clients␣..." 
 
UDP_sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM) 
UDP_sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1) 
UDP_sock.bind((’’, TCP_sock.getsockname()[1])) 
print "Waiting␣for␣UDP␣clients␣..." 
 
UDP_Handler(UDP_sock).start() 
 
while True: # Serve forever. 
    TCP_client = TCP_sock.accept() 
    TCP_Handler(TCP_client).start()
#!/usr/bin/python 
 
’’’An UDP client for the previous concurrent server’’’ 
 
# See: http://wiki.python.org/moin/UdpCommunication 
# See: http://docs.python.org/2/library/socket.html 
 
import socket 
import struct 
import random 
 
sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM) 
 
while True: 
    value = int(255random.random()) 
    sock.sendto(struct.pack(’>H’, value), (’localhost’, 9999)) 
    print ’Sent’, value, 
    (message, sender) = sock.recvfrom(struct.calcsize(’>H’)) 
    value = struct.unpack(’>H’, message) 
    print ’and␣received’, value