Почему мой серверный сокет не получает данные? ПитонPython

Программы на Python
Ответить
Anonymous
 Почему мой серверный сокет не получает данные? Питон

Сообщение Anonymous »

У меня возникли проблемы с программированием сокетов. Я начал изучать эту тему и создал небольшое приложение эхо-сервер/клиент из руководства, после чего я создал его многопоточную версию для нескольких клиентов. Он отлично работает со следующим кодом:
Сервер:

Код: Выделить всё

from Rest_Endpoint.thread import ConnectionThread

HOST = ''
PORT = 6000

def start_server():
server: socket = socket.socket(family=socket.AF_INET, type=socket.SOCK_STREAM)
server.bind((HOST,PORT))
server.listen(10)
print('listen to port', PORT)
server.setblocking(False)

while True:
try:
conn, addr = server.accept()  # Will throw BlockingIOError if no connections
print('Connected by:', addr)
thread_spawn(conn, addr)
except BlockingIOError:
# No incoming connection; continue the loop
continue
except Exception as e:
print(f'Unexpected error: {e}')
break
Порожденная тема:

Код: Выделить всё

from Rest_Endpoint.thread import ConnectionThread

HOST = ''
PORT = 6000

def start_server():
server: socket = socket.socket(family=socket.AF_INET, type=socket.SOCK_STREAM)
server.bind((HOST,PORT))
server.listen(10)
print('listen to port', PORT)
server.setblocking(False)

while True:
try:
conn, addr = server.accept()  # Will throw BlockingIOError if no connections
print('Connected by:', addr)
thread_spawn(conn, addr)
except BlockingIOError:
# No incoming connection; continue the loop
continue
except Exception as e:
print(f'Unexpected error: {e}')
break

Клиент:

Код: Выделить всё

# Echo client program
import socket

HOST = ''    # The remote host
PORT = 6000              # The same port as used by the server
with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as s:
try:
# Connect to the server
s.connect((HOST, PORT))
print(f'Connected to server at {HOST}:{PORT}')

while True:
# message = input()
# bmessage = (message + '\n').encode('utf-8')
s.sendall(b'test')
# print(bmessage)'

except ConnectionRefusedError:
print(f"Could not connect to server at {HOST}:{PORT}. Ensure the server is running.")
except Exception as e:
print(f"An error occurred: {e}")
Когда я запускаю клиентскую программу, я получаю следующее:

Код: Выделить всё

Connected by ('127.0.0.1', 51804)
waiting for message 
prints data:
b'testtesttesttesttesttesttesttesttesttesttesttesttesttesttesttesttesttesttesttesttesttesttesttesttesttesttesttesttesttesttesttesttesttesttesttesttesttesttesttesttesttesttesttesttesttesttesttesttesttesttesttesttesttesttesttesttesttesttesttest'
Я понимаю, что tcp — это поток, и из-за while True Loop я получаю этот результат нескольких тестов подряд.
Но когда я пытаюсь переключить клиентский код на:

Код: Выделить всё

 while True:
message = input()
bmessage = (message).encode('utf-8')
s.sendall(b'test')
print(bmessage)

Я не получаю никаких сообщений на стороне сервера и не понимаю, почему. Подключается, но данных не получаю.
Может кто-нибудь поможет мне с объяснением.
Заранее спасибо.

Подробнее здесь: https://stackoverflow.com/questions/793 ... ata-python
Ответить

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

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

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

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

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