Study Vault Search notes, aliases and full text
Graph
ConceptDBISAI-written · not yet proofread

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 sideClient side
create a socket and bind it to a given portconnect to the server socket (needs host name + port)
listen on that port for incoming connectionsthe OS assigns a unique port on the client machine automatically
wait (accept), read request, compute result, send resultsend 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, Java java.net.ServerSocket, C++ boost::asio (asio = asynchronous IO).
  • Read in rounds. recv(num_bytes) returns at most num_bytes bytes, 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\n that ends the header (HTTP Server).
  • The data are bytes, not strings. Converting them needs an explicit Character Encoding (decode after receiving, encode before 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) or curl -v http://<host>:<port> (-v prints 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#

Search

Type In
↑ ↓ move ↵ open ⇥ next section Ctrl↵ results page Prefix # to search text only