How to Create Simple Server-Client Program Using Socket Programming in Python?
Share
Condition for Creating Simple Server-Client Program Using Socket Programming in Python
Description:
A simple server in Python can be created using the socket module, which allows you to establish a
connection to the network, listen for client requests, and send/receive data.
A server typically listens on a specific port and waits for incoming client connections.
Step-by-Step Process
Create a socket object:
Create a socket object to handle communication.
Bind the server:
Bind the server to a specific IP address and port.
Listen for connections:
Listen for incoming client connections.
Accept connection:
Accept the connection and interact with the client (send/receive messages).
Close connection:
Close the connection when done.
Sample Code
#Simple server program using socket module
#Server side
import socket
server_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
host = '127.0.0.1'
port = 12345
server_socket.bind((host, port))
server_socket.listen(1)
print(f"Server listening on {host}:{port}...")
client_socket, client_address = server_socket.accept()
print(f"Connection established with {client_address}")
client_socket.sendall(b"Hello, client! You are connected to the server.")
client_socket.close()
server_socket.close()
#Client-side
import socket
client_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
host = '127.0.0.1'
port = 12345
client_socket.connect((host, port))
response = client_socket.recv(1024)
print("Received from server:", response.decode())
client_socket.close()