In this Python Network Programming article we want to learn about Network Programming in Python Using Sockets, for this purpose we are going to use socket module in Python. socket module allows you to create sockets and establish connections between clients and servers, so first of all let’s talk that what is socket ?
What is a Socket?
Socket is an endpoint of two way communication link between two programs running on the network. in network programming socket provides a way for communication between two programs over network.
In Python socket module provides low level interface for creating and working with sockets. socket module provides classes for handling client side and server side of network programming.
For creating a socket in Python, you can use socket() function from socket module. socket() function takes two parameters, socket family and socket type. socket family specifies protocol family of socket, and socket type specifies type of socket.
This is an example of socket in Python
1 2 3 4 |
import socket # Create TCP/IP socket sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM) |
For connecting to a server we can use connect() method of socket object. connect() method takes single parameter, which is a tuple containing the address and port number of the server.
This is our code for server connection
1 2 3 4 5 6 7 8 |
import socket # Create TCP or IP socket sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM) # Connect socket to the server server_address = ('localhost', 5000) sock.connect(server_address) |
After that the socket connection has been established, you can send and receive data using socket send() and recv() methods.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 |
import socket # Create TCP or IP socket sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM) # Connect socket to server server_address = ('localhost', 5000) sock.connect(server_address) # Send data to server message = 'Hello server' sock.sendall(message.encode()) # Receive data from server data = sock.recv(1024) print('Received:', data.decode()) # Close socket sock.close() |
Learn More
- Python Socket Programming Examples
- Python Socket Programming for Beginners
- Python Socket Server Tutorial
- Python Socket Client Example
- TCP Socket Programming in Python
- Socket Programming in Python with select()
- Simple Socket Programming in Python
- UDP Socket Programming in Python
- Python Socket Programming Basics