Я использую программирование сокетов на 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
Как создать новое клиентское соединение со стороны сервера с помощью программирования сокетов Python? ⇐ Python
Программы на Python
1764558923
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()
Подробнее здесь: [url]https://stackoverflow.com/questions/79832908/how-to-create-a-new-client-connection-from-the-server-side-using-python-socket-p[/url]
Ответить
1 сообщение
• Страница 1 из 1
Перейти
- Кемерово-IT
- ↳ Javascript
- ↳ C#
- ↳ JAVA
- ↳ Elasticsearch aggregation
- ↳ Python
- ↳ Php
- ↳ Android
- ↳ Html
- ↳ Jquery
- ↳ C++
- ↳ IOS
- ↳ CSS
- ↳ Excel
- ↳ Linux
- ↳ Apache
- ↳ MySql
- Детский мир
- Для души
- ↳ Музыкальные инструменты даром
- ↳ Печатная продукция даром
- Внешняя красота и здоровье
- ↳ Одежда и обувь для взрослых даром
- ↳ Товары для здоровья
- ↳ Физкультура и спорт
- Техника - даром!
- ↳ Автомобилистам
- ↳ Компьютерная техника
- ↳ Плиты: газовые и электрические
- ↳ Холодильники
- ↳ Стиральные машины
- ↳ Телевизоры
- ↳ Телефоны, смартфоны, плашеты
- ↳ Швейные машинки
- ↳ Прочая электроника и техника
- ↳ Фототехника
- Ремонт и интерьер
- ↳ Стройматериалы, инструмент
- ↳ Мебель и предметы интерьера даром
- ↳ Cантехника
- Другие темы
- ↳ Разное даром
- ↳ Давай меняться!
- ↳ Отдам\возьму за копеечку
- ↳ Работа и подработка в Кемерове
- ↳ Давай с тобой поговорим...
Мобильная версия