How to Create a Simple Server Using Socket Module in Python?
Share
Condition for Create a Simple Server Using Socket Module in Python
Description:
A server-client program in Python allows two applications to communicate over a network using sockets.
The server listens for incoming connections from clients, while the client sends requests to the server.
This interaction can be used for various tasks like message exchange or data transfer.
Step-by-Step Process
Import the socket Library:
Use the socket module to create the server and client.
Server Side: Create a Server Socket:
The server creates a socket, binds it to a specific IP address and port, and listens for incoming client connections.
Accept Client Connection:
The server accepts a connection from the client and can receive data from it.
Send Data:
The server can respond to the client by sending data back through the connection.
Close the Connection:
Once the communication is done, the server closes the connection.
Client Side: Create a Client Socket:
The client creates a socket and connects to the server.
Send Data:
The client sends a request or message to the server.
Receive Data:
The client receives a response from the server.
Close the Connection:
After communication, the client closes the connection.
Sample Code
#Server-program
print("Server Side:")
import socket
server_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
server_socket.bind(('localhost', 12345))
server_socket.listen(5)
print("Server is listening on port 12345...")
client_socket, client_address = server_socket.accept()
print(f"Connection established with {client_address}")
client_message = client_socket.recv(1024).decode('utf-8')
print(f"Received message: {client_message}")
server_response = "Hello, Client! Message received."
client_socket.send(server_response.encode('utf-8'))
client_socket.close()
server_socket.close()
#Client-Program
print("Client side:")
import socket
client_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
client_socket.connect(('localhost', 12345))
message = "Hello, Server! This is a message from the client."
client_socket.send(message.encode('utf-8'))
server_response = client_socket.recv(1024).decode('utf-8')
print(f"Received from server: {server_response}")
client_socket.close()