Python provides several libraries for network programming, such as the socket
module, which helps you to work with network connections.
Here is an example of a simple server and client using Python's socket
module:
import socket
server = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
server.bind(('localhost', 8080))
server.listen(5)
print("Server started, waiting for connection...")
while True:
client_socket, client_address = server.accept()
print(f"Connection from {client_address}")
client_socket.send("Hello, Client!".encode())
client_socket.close()
import socket
client = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
client.connect(('localhost', 8080))
message = client.recv(1024)
print(f"Message from server: {message.decode()}")
client.close()
Modify the server to send a custom message to the client, and have the client send a response back to the server.
socket
module?Answers: The socket
module is used to work with network connections. You can establish a connection by calling connect()
on a client socket object.