-
Notifications
You must be signed in to change notification settings - Fork 0
socket
jasper-zanjani edited this page Oct 5, 2020
·
2 revisions
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)
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'))
Define port on which to listen for connections.
serversocket.bind(('localhost',80))
Connect to a remote socket in one direction
client_socket.connect(('www.packtpub.com',80))
Convert a domain name into IPv4 address
socket.gethostbyname('packtpub.com') # '83.166.169.231'
Defaults to localhost with no arguments
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.bind((socket.gethostname(),1234))
Get protocol name from port number
socket.getservbyport(80) # 'http'
Listen to a maximum of 10 connections
serversocket.listen(10)
Receive bytestream from server
msg = s.recv(1024)
print(msg.decode('utf-8'))
- argparse ?
- array ?
- asyncio ?
- bisect ?
- csv ?
- ctypes ?
- curses ?
- datetime ?
- functools ?
- getpass ?
- glob ?
- heapq ?
- http ?
- json ?
- logging ?
- optparse ?
- os ?
- pathlib ?
- platform ?
- pythonnet ?
- random ?
- socket ?
- subprocess ?
- sqlite3 ?
- sys ?
- termcolor ?
- threading ?
- trace ?
- typing ?
- unittest ?
- urllib ?
- venv ?
- weakref ?
- winrm ?