Network Socket
Also Socket · Socket Communication
A socket is an endpoint of a communication channel between two processes, identified by its machine (host) and a number unique on that machine (port); data is exchanged through it as bytes.
Formula#
The basic request–response protocol:
| Server side | Client side |
|---|---|
| create a socket and bind it to a given port | connect to the server socket (needs host name + port) |
| listen on that port for incoming connections | the OS assigns a unique port on the client machine automatically |
| wait (accept), read request, compute result, send result | send request, wait for result |
Server side in Python (course template):
from socket import *
server_socket = socket(AF_INET, SOCK_STREAM) # IPv4 + TCP
server_socket.setsockopt(SOL_SOCKET, SO_REUSEADDR, 1) # reuse port after a restart
server_socket.bind(("0.0.0.0", port)) # listen on all interfaces of this machine
server_socket.listen()
connection, client_address = server_socket.accept() # blocks until a client connects
connection.settimeout(5.0)
request_data = bytearray()
while (...): request_data.extend(connection.recv(num_bytes)) # read in rounds
connection.sendall(...) # answer data as byte array
connection.close()
accept() returns a new socket connection for this one client; the server socket keeps listening for further clients.
Properties#
- Every major language has a standard library for sockets: Python
socket, Javajava.net.ServerSocket, C++boost::asio(asio = asynchronous IO). - Read in rounds.
recv(num_bytes)returns at mostnum_bytesbytes, possibly fewer, possibly an empty chunk. There is no universal “end of message” token, so the receiver loops until the application protocol says the message is complete. For an HTTP request without a body this is the empty line\r\n\r\nthat ends the header (HTTP Server). - The data are bytes, not strings. Converting them needs an explicit Character Encoding (
decodeafter receiving,encodebefore sending). - For a web application only the server has to be written; the browser is the client. For testing:
telnet <host> <port>(type the request by hand) orcurl -v http://<host>:<port>(-vprints the headers). - Sheet 9 requires robustness against all client behaviours: connecting and aborting, connecting and sending nothing (hence the timeout), sending the request in several packets, some of them empty.
Example#
Sources#
- Slides 09, p. 5 (socket, host, port), p. 6 (protocol), pp. 7–8 (server code), p. 9 (client, testing)
- DBIS_VL09 > What is a socket, DBIS_VL09 > Request–response protocol, DBIS_VL09 > Server implementation in Python, DBIS_VL09 > Client side and testing
- Sheet 09, Exercise 1.1 (robustness requirements)
- DBIS Exam WS1819 (not published), Task 4.2