I'm using python socket programming to build a mock VPN service. the way I want it to work is that the server is launched, then the user client (Host-U) is launched. The Server should send a message to the Host-U asking the user to make a selection of which site they wish to connect to. Once the user makes their selection, the server should take that info and open a new connection with another active client (Host_V), and begin tunneling data between the two clients. Is there anyway to create the new connection at the server side of the process? all the examples I found online show the server being the one to listen for new connections and then accept them when the client reaches out.
Here is the code I'm working with as a base. How can I modify this to achieve my end goal?
# Client IP and Port configuration
HOST = '127.0.0.1' # Server's IP address (localhost)
PORT = 65432 # Port the server is listening on# Start the client
def start_client():
with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as client_socket:
client_socket.connect((HOST, PORT)) # Connect to the server
while True:
message = input("Enter your message (type 'exit' to quit): ")
if message.lower() == 'exit':
print("Closing the connection...")
break client_socket.sendall(message.encode()) # Send the message to the server
data = client_socket.recv(1024) # Receive the response from the server
print(f"Server response: {data.decode()}")
print("Connection terminated.")if __name__ == "__main__":
start_client()
# Server IP and Port configuration
import socket
import threading
# Server IP and Port configuration
HOST = '10.9.0.7' # Server IP (localhost)
PORT = 4433 # Port for client connections# Function to manage client connections
def handle_client(conn, addr):
print(f"Connection established with {addr}.")
while True:
try:
data = conn.recv(1024) # Receive data from the client
if not data:
break # Terminate the connection if no data is received
print(f"Received from {addr}: {data.decode()}")
conn.sendall(f"Server response: {data.decode()}".encode()) # Send the received data back to the client
except ConnectionResetError:
print(f"Client {addr} has disconnected.")
break
conn.close()
print(f"Connection with {addr} closed.")# Start the server
def start_server():
with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as server_socket:
server_socket.bind((HOST, PORT))
server_socket.listen()
print(f"Server listening on {HOST}:{PORT}...")
while True:
conn, addr = server_socket.accept() # Accept a client connection
thread = threading.Thread(target=handle_client, args=(conn, addr))
thread.start() # Start a new thread for each client
print(f"Active connections: {threading.activeCount() - 1}")
if __name__ == "__main__":
start_server()