Server Code
First, you must create a server ton your PC/laptop. This server can handle multi-client which means that the server can receive data from multiple clients. Also, the server is capable to send data to all clients. Here is the example.
import socket
import threading
# Set up the server address and port
server_address = ('192.168.123.100', 20002)
# Create a TCP/IP socket
server_sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
server_sock.bind(server_address)
server_sock.listen(5) # Set a queue for a maximum of 5 connections
print(f"Server is listening on {server_address}")
# List to keep track of connected clients
clients = []
def handle_client(connection, client_address):
"""Function to handle client connection."""
print(f"Connection from {client_address}")
clients.append(connection) # Add new client to the list
try:
while True:
# Receive data from client
data = connection.recv(1024)
if not data:
print(f"No data from {client_address}. Closing connection.")
break # No more data from the client
print(f"Received from {client_address}: {data.decode()}")
# Forward the received message to all clients
forward_message(data, connection)
except Exception as e:
print(f"Error with {client_address}: {e}")
finally:
clients.remove(connection) # Remove client from list on disconnect
connection.close()
print(f"Connection with {client_address} closed.")
def forward_message(message, sender_connection):
"""Function to forward the message to all connected clients except the sender."""
for client in clients:
if client != sender_connection: # Don't send the message back to the sender
try:
client.sendall(message) # Forward message to the other clients
except Exception as e:
print(f"Failed to send message to {client}: {e}")
while True:
connection, client_address = server_sock.accept()
# Start a new thread for each client connection
client_thread = threading.Thread(target=handle_client, args=(connection, client_address))
client_thread.start()
What the code basically do is creating a server and listening up to 5 clients. Also, you can modify the code if you only want to send data to a specific ip address.
Client Code (PC or laptop)
NOTE!!!
Make sure your IP Address is in the same range with server’s IP (In this case the ip should be 192.168.123.xxx). If you unsure what your IP address is, you can check it with ipconfig on command prompt.
import socket
import threading
# Set up the server address and port
server_address = ('192.168.123.100', 20002)
def receive_messages(sock):
"""Function to receive messages from the server."""
while True:
try:
message = sock.recv(1024)
if not message:
print("Disconnected from the server.")
break
print(f"Received: {message.decode()}")
except Exception as e:
print(f"Error receiving message: {e}")
break
def main():
# Create a TCP/IP socket
client_sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
try:
# Connect to the server
client_sock.connect(server_address)
print(f"Connected to server at {server_address}")
# Start a thread to receive messages from the server
threading.Thread(target=receive_messages, args=(client_sock,), daemon=True).start()
while True:
# Get user input and send it to the server
message = input("Enter message to send (or 'exit' to quit): ")
if message.lower() == 'exit':
print("Exiting...")
break
client_sock.sendall(message.encode())
except Exception as e:
print(f"Error: {e}")
finally:
client_sock.close()
print("Connection closed.")
if __name__ == "__main__":
main()
This is a simple example of client socket for PC. For robot, you can see the example on another tutorial. Your laptop or robot should now can communicate with the server: