Give me example of simple connection of two Python scripts by ip address and port. It…
- User
Give me example of simple connection of two Python scripts by ip address and port. It support transmit packets of data. Simplify code as possible
- Assistant
Below is a simplified example of two Python scripts that connect over an IP address and a port using the socket library. The first script will act as the server, listening for a connection, and the second script will act as the client, connecting to the server to send a message.
Server.py (Listens on localhost, port 12345):
import socket # Create a socket object server_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM) # Get local machine name (you could also set this as 'localhost') host = '127.0.0.1' port = 12345 # Bind to the port server_socket.bind((host, port)) # Start listening for a connection (with a maximum of 1 queued connection) server_socket.listen(1) print(f"Listening on {host}:{port}") # Wait for client connection client_socket, addr = server_socket.accept() print("Got a connection from %s" % str(addr)) # Receive up to 1024 bytes from the client data = client_socket.recv(1024) print(f"Received: {data.decode('utf-8')}") # Close the connection client_socket.close()
Other models, same or similar prompt
Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.