Как создать новое клиентское соединение со стороны сервера с помощью программирования сокетов Python?Python

Программы на Python
Ответить
Anonymous
 Как создать новое клиентское соединение со стороны сервера с помощью программирования сокетов Python?

Сообщение Anonymous »

Я использую программирование сокетов на Python для создания имитации службы VPN. Я хочу, чтобы это работало: запускается сервер, затем запускается пользовательский клиент (Host-U). Сервер должен отправить сообщение Host-U с просьбой к пользователю выбрать, к какому сайту он хочет подключиться. Как только пользователь сделает свой выбор, сервер должен принять эту информацию и открыть новое соединение с другим активным клиентом (Host_V) и начать туннелирование данных между двумя клиентами. Есть ли способ создать новое соединение на стороне сервера? все примеры, которые я нашел в Интернете, показывают, что сервер прослушивает новые соединения, а затем принимает их, когда клиент обращается к ним.
Вот код, с которым я работаю в качестве основы. Как я могу изменить это для достижения конечной цели?
# 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()


Подробнее здесь: https://stackoverflow.com/questions/798 ... n-socket-p
Ответить

Быстрый ответ

Изменение регистра текста: 
Смайлики
:) :( :oops: :roll: :wink: :muza: :clever: :sorry: :angel: :read: *x)
Ещё смайлики…
   
К этому ответу прикреплено по крайней мере одно вложение.

Если вы не хотите добавлять вложения, оставьте поля пустыми.

Максимально разрешённый размер вложения: 15 МБ.

Вернуться в «Python»