我第一次使用Python(3.7.3),并且试图构建一个聊天服务器,该服务器接收来自客户端的消息并将其发送给所有其他客户端。
问题是-使用recv(),
时,它会分别向我发送每个字符。
如何解决此问题?
我编写了recv_line
函数,该函数假定在用户按下Enter键之前一直接收字符:
import selectors
import socket
import sys
if len(sys.argv) != 4:
print("Correct usage: python3 ChatServer.py IP_address port
Clients_number")
exit()
BUFFER_SIZE = 1024
host = str(sys.argv[1])
port = int(sys.argv[2])
clients_num = int(sys.argv[3])
sel = selectors.DefaultSelector()
connections = []
def read(conn, mask):
data = recv_line(conn)
if data:
print(repr(conn.getpeername()), 'sent', repr(data))
broadcast(conn, data)
else:
print('closing', conn)
sel.unregister(conn)
conn.close()
connections.remove(conn)
def recv_line(conn):
total_data = ""
while True:
data = conn.recv(BUFFER_SIZE)
if data:
total_data += data.decode('utf8')
if '\n' == data:
return total_data.encode('utf8')
else:
return 0
def accept(sock, mask):
conn, addr = sock.accept()
print('accepted connection from', addr)
connections.append(conn)
conn.setblocking(False)
sel.register(conn, selectors.EVENT_READ, read)
notify_clients_about_new_entry(conn, addr
sock = socket.socket()
sock.bind((host, port))
sock.listen(clients_num)
sock.setblocking(False)
sel.register(sock, selectors.EVENT_READ, accept)
while True:
events = sel.select()
for key, mask in events:
callback = key.data
callback(key.fileobj, mask)
我没有收到一条完整的消息,而不仅仅是一次收到一个字符,而是在客户端开始写消息时出现了错误:
File "C:/Users/USER/Desktop/pycharmProjects/ChatServer.py", line 27, in recv_line
data = conn.recv(BUFFER_SIZE)
BlockingIOError: [WinError 10035] A non-blocking socket operation could not be completed immediately