There is certainly some confusion with sockets, as my flatmate put it; sockets connect stuff together right?
Wikipedia puts it a little clearer with:
So the hello world of sockets would have to be an echo server. Let's create a basic Python3 socket server that will listen on IPv6 and repeat what it hears.
The Python Howto guide for sockets starts with this:
Hopefully this server program is easy enough to understand, it is based very closely on the socket example in the Python documentation. My small alterations cause the server to listen only on IPv6, and will spin off a new thread when a client connects, and the server keeps listening for more connections. Part two of "Hello World in Sockets" is the client which follows a sequence of:
That's the simple low level stuff out of the way! I'd like to point out that Python does have a higher level socket api that could easily implement our echo server, have a look at the TCP Socket examples that use the socketserver module. Now the stuff I'm really interested in, using sockets with Bluetooth and CAN!
Wikipedia puts it a little clearer with:
sockets are inter-process communication endpointsThat sounds pretty boring but I promise you can do some fairly interesting things with them. Sockets are a core part of the operating system, and a socket API is used to direct how the operating system should use sockets.
So the hello world of sockets would have to be an echo server. Let's create a basic Python3 socket server that will listen on IPv6 and repeat what it hears.
The Python Howto guide for sockets starts with this:
Sockets are used nearly everywhere, but are one of the most severely misunderstood technologies around.On the server side, you follow these steps:
- Create a socket (possibly after querying the system for information)
- Bind the socket, which assigns the socket to an address
- Listen prepares it for incoming connections
- Accept an incoming connection from a client, giving you a new dedicated socket to communicate with that client.
#!/usr/bin/env python3
# Echo consumer_server program
import socket
import threading
host = "localhost" # Symbolic name meaning all available interfaces
random_port = 50007 # Arbitrary non-privileged port
def echo(conn, addr):
while True:
data = conn.recv(1024)
if not data: break
print('Server heard "{}"'.format(data.decode()))
conn.send(data)
conn.close()
def consumer_server(address_family, socket_type, protocol, canonname, sa):
try:
s = socket.socket(address_family, socket_type, protocol)
except OSError as msg:
print(msg)
print('could not open socket')
return
# Tell the OS it can reuse a socket if it wants
s.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
try:
s.bind(sa)
# tells the OS that we want it to queue up to 5 connect requests
s.listen(5)
except OSError as msg:
s.close()
raise SystemExit('Socket binding/listening failed...')
while True:
try:
conn, addr = s.accept()
print('Connected by', addr)
threading.Thread(target=echo, args=(conn, addr)).start()
except KeyboardInterrupt:
s.close()
raise SystemExit()
address_info = socket.getaddrinfo(host, random_port,
socket.AF_UNSPEC, socket.SOCK_STREAM,
0, socket.AI_PASSIVE)[-1]
consumer_server(*address_info)
- Creating a socket (also using system information from getaddrinfo)
- connecting to the socket
# Echo client program
import socket
HOST = 'localhost' # The remote host
PORT = 50007 # The same port as used by the server
af, socktype, proto, _, sa = socket.getaddrinfo(HOST,
PORT,
socket.AF_UNSPEC,
socket.SOCK_STREAM)[0]
try:
s = socket.socket(af, socktype, proto)
s.connect(sa)
except socket.error:
s.close()
raise SystemExit('Error: Could not open socket :-/')
def send_and_receive(outgoing_data):
s.sendall(outgoing_data)
incoming_data = s.recv(1024)
print('Received', incoming_data.decode())
for data in [b'Hello, world', '汉语/漢語 Hànyǔ'.encode()]:
send_and_receive(data)
s.close()
That's the simple low level stuff out of the way! I'd like to point out that Python does have a higher level socket api that could easily implement our echo server, have a look at the TCP Socket examples that use the socketserver module. Now the stuff I'm really interested in, using sockets with Bluetooth and CAN!