Certainly! You can create a simple Python script that listens for a "ping" message and replies with "pong". You can use a basic TCP or UDP socket for this. Below, I'll provide an example using both TCP and UDP.
TCP Example
python
import socket
def tcp_ping_pong_server(host='localhost', port=65432):
# Create a TCP/IP socket
with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as server_socket:
# Bind the socket to the address and port
server_socket.bind((host, port))
server_socket.listen()
print(f'Server listening on {host}:{port}')
while True:
conn, addr = server_socket.accept()
with conn:
print(f'Connected by {addr}')
while True:
data = conn.recv(1024)
if not data:
break
message = data.decode('utf-8')
print(f'Received: {message}')
if message == 'ping':
conn.sendall(b'pong')
if __name__ == '__main__':
tcp_ping_pong_server()
UDP Example
python
import socket
def udp_ping_pong_server(host='localhost', port=65432):
# Create a UDP socket
with socket.socket(socket.AF_INET, socket.SOCK_DGRAM) as server_socket:
server_socket.bind((host, port))
print(f'Server listening on {host}:{port}')
while True:
data, addr = server_socket.recvfrom(1024)
message = data.decode('utf-8')
print(f'Received from {addr}: {message}')
if message == 'ping':
server_socket.sendto(b'pong', addr)
if __name__ == '__main__':
udp_ping_pong_server()
How to Run the Code
Choose one of the examples (TCP or UDP) and save the code into a Python file, for example ping_pong_server.py.
Run the server script using Python:
bash
python ping_pong_server.py
You can test the server using a simple client:
TCP Client Example
python
import socket
def tcp_ping_pong_client(host='localhost', port=65432):
with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as client_socket:
client_socket.connect((host, port))
client_socket.sendall(b'ping')
data = client_socket.recv(1024)
print('Received', repr(data))
if __name__ == '__main__':
tcp_ping_pong_client()
UDP Client Example
python
import socket
def udp_ping_pong_client(host='localhost', port=65432):
with socket.socket(socket.AF_INET, socket.SOCK_DGRAM) as client_socket:
client_socket.sendto(b'ping', (host, port))
data, _ = client_socket.recvfrom(1024)
print('Received', repr(data))
if __name__ == '__main__':
udp_ping_pong_client()
How to Run the Client
Save the appropriate client code into a separate Python file, for example ping_pong_client.py.
Run the client script after starting the server:
bash
python ping_pong_client.py
When you run the client, it will send "ping" to the server, and the server will respond with "pong".