Networking in Python? - with practical example
Networking in Python allows us to establish connections, send and receive data over networks. We can create network applications such as chat programs, web servers, and more using the networking capabilities provided by Python.
**Example 1: Creating a simple TCP server**
Step 1: Import the necessary library socket to create a socket object.
Step 2: Define the host and port on which the server will listen for connections.
Step 3: Create a socket object using socket.socket() and bind it to the host and port.
Step 4: Listen for incoming connections using socket.listen() .
Step 5: Accept incoming connections and handle them accordingly.
**Example 2: Creating a simple TCP client** Step 1: Import the necessary library socket to create a socket object. Step 2: Define the server's host and port to which the client will connect. Step 3: Create a socket object using socket.socket() and connect it to the server. Step 4: Send data to the server using socket.send() . Step 5: Receive data from the server using socket.recv() .
By following these steps, you can easily create TCP server and client applications in Python to establish network connections and send/receive data.
import socket host = '127.0.0.1' port = 12345 server_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM) server_socket.bind((host, port)) server_socket.listen(5) print(f"Server is listening on {host}:{port}") client_socket, addr = server_socket.accept() print(f"Connection from {addr}") data = client_socket.recv(1024) print(f"Received data: {data.decode()}") client_socket.close() server_socket.close()
**Example 2: Creating a simple TCP client** Step 1: Import the necessary library socket to create a socket object. Step 2: Define the server's host and port to which the client will connect. Step 3: Create a socket object using socket.socket() and connect it to the server. Step 4: Send data to the server using socket.send() . Step 5: Receive data from the server using socket.recv() .
import socket host = '127.0.0.1' port = 12345 client_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM) client_socket.connect((host, port)) message = "Hello, Server!" client_socket.send(message.encode()) data = client_socket.recv(1024) print(f"Received data from server: {data.decode()}") client_socket.close()
By following these steps, you can easily create TCP server and client applications in Python to establish network connections and send/receive data.
Comments
Post a Comment