[Ortega]: # "Jose Manuel Ortega, et al. Learning Python Networking." :point_right: [Sockets tutorial](https://youtu.be/Lbfe3-v7yE0) The socket module is Python's standard interface for the transport layer. Sockets can be classified by **`family`** - **`AF_INET`** Internet - `AF_UNIX` for UNIX sockets and **`type`**: - **`SOCK_STREAM`** TCP - `SOCK_DGRAM` UDP These enum values are required upon initialization of a socket object: [Ortega][Ortega]: 25 ```py client_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM) ``` #### Simple implementation Websocket server ```py import socket s = socket.socket(socket.AF_INET, socket.SOCK_STREAM) s.bind((socket.gethostname(),1234)) s.listen(5) while True: clientsocket, address = s.accept() print(f'Connection from {address} has been established') clientsocket.send(bytes('Welcome to the server', 'utf-8')) ``` Websocket client ```py import socket s = socket.socket(socket.AF_INET, socket.SOCK_STREAM) s.connect((socket.gethostname(), 1234)) msg = s.recv(1024) print(msg.decode('utf-8')) ``` ### API - [socket.bind](#socketbind) - [socket.connect](#socketconnect) - [socket.gethostname](#socketgethostname) - [socket.listen](#socketlisten) - [socket.recv](#socketrecv) #### socket.bind Define port on which to listen for connections. ```py serversocket.bind(('localhost',80)) ``` #### socket.connect Connect to a remote socket in one direction ```py client_socket.connect(('www.packtpub.com',80)) ``` #### socket.gethostbyname Convert a domain name into IPv4 address ```py socket.gethostbyname('packtpub.com') # '83.166.169.231' ``` #### socket.gethostname Defaults to **localhost** with no arguments ```py s = socket.socket(socket.AF_INET, socket.SOCK_STREAM) s.bind((socket.gethostname(),1234)) ``` #### socket.getservbyport Get protocol name from port number ```py socket.getservbyport(80) # 'http' ``` #### socket.listen Listen to a maximum of 10 connections ```py serversocket.listen(10) ``` #### socket.recv Receive bytestream from server ```py msg = s.recv(1024) print(msg.decode('utf-8')) ```