~/Socket Programming Basics in Python

Jan 10, 2022


Socket programming in Python enables direct communication over a network interface. Use the standard socket library for low level network operations.

To create a TCP server

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
import socket

s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.bind(('localhost', 8080))
s.listen(1)
conn, addr = s.accept()
data = conn.recv(1024)
conn.sendall(b'Hello, world')
conn.close()
s.close()

To connect as a client

1
2
3
4
5
6
7
import socket

s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.connect(('localhost', 8080))
s.sendall(b'Hello, server')
data = s.recv(1024)
s.close()

You can use socket.AF_INET for IPv4 and socket.SOCK_STREAM for TCP connections. Always close sockets to avoid resource leaks.

Read the official Python docs for more on creating UDP sockets, handling multiple connections, and error management.

Tags: [python] [sockets]