Skip to content
jasper-zanjani edited this page Oct 5, 2020 · 2 revisions

👉 Sockets tutorial

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: 25

client_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)

Simple implementation

Websocket server

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

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

Define port on which to listen for connections.

serversocket.bind(('localhost',80))

socket.connect

Connect to a remote socket in one direction

client_socket.connect(('www.packtpub.com',80))

socket.gethostbyname

Convert a domain name into IPv4 address

socket.gethostbyname('packtpub.com') # '83.166.169.231'

socket.gethostname

Defaults to localhost with no arguments

s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.bind((socket.gethostname(),1234))

socket.getservbyport

Get protocol name from port number

socket.getservbyport(80) # 'http'

socket.listen

Listen to a maximum of 10 connections

serversocket.listen(10)

socket.recv

Receive bytestream from server

msg = s.recv(1024)
print(msg.decode('utf-8'))
Clone this wiki locally