我正在编码一个python套接字服务器,当您连接时,使用用“:”分隔的用户名和密码登录时,只要您在所连接的服务器中说些什么,它就会使用函数“ Broadcast()”将消息发送给其他所有人/ p>
但是当我尝试登录时,它不会说“ Welcome”(欢迎)。它只是什么都不做,基本上无法登录。
我正在使用PuTTY连接到它。
代码:
import socket
import threading
from thread import start_new_thread
connect = ""
conport = 8080
clients = []
def client_thread(conn):
fd = open("login.txt", "r")
def username(conn, prefix="Username: "):
conn.send(prefix)
return conn.recv(2048)
def password(conn, prefix="Password: "):
conn.send(prefix)
return conn.recv(2048)
username = username(conn)
password = password(conn)
for line in fd:
line = line.strip()
if line.split(":")[0] in username and line.split(":")[1] in password:
while True:
conn.send("Welcome")
message = conn.recv(2048)
print(message)
if message:
broadcast(message, conn)
else:
remove(conn)
if not message:
break
def start_client():
sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
sock.bind((connect, conport))
sock.listen(1)
while True:
conn, addr = sock.accept()
clients.append(conn)
start_new_thread(client_thread, (conn,))
sock.close()
def broadcast(message, connection):
for machine in clients:
if machine != connection:
try:
machine.sendall(message)
except:
machine.close()
remove(machine)
def remove(connection):
if connection in clients:
clients.remove(connection)
threading.Thread(target=start_client).start()
预期结果:
Username: Admin
Password: 1234
Welcome
实际结果:
Username: Admin
Password: 1234
login.txt
Admin:1234
Nimda:4321
能帮我吗?它无法正确登录:c
答案 0 :(得分:0)
您的代码有很多问题。
您可以使用具有相同名称的变量来隐藏局部函数username
和password
。
您不要关闭fd
(考虑使用with
语句)
您的逻辑看起来客户应该看到的第一件事是Username:
,而不是Welcome
。
您极有可能在代码中混淆str
和bytes
。
以下代码可在 Python3 上运行,但仍然非常错误:
import socket
import threading
from _thread import start_new_thread
connect = ""
conport = 8080
clients = []
def receive(conn, prefix):
conn.send(prefix)
data = b''
while b'\n' not in data:
portion = conn.recv(1024)
if portion:
data += portion
return data.decode('utf-8').strip()
def client_thread(conn):
with open("login.txt", "r") as fd:
username = receive(conn, b'Username: ')
password = receive(conn, b'Password: ')
for line in fd:
u, p = line.strip().split(':')
if u == username and p == password:
while True:
conn.send(b'Welcome')
message = conn.recv(2048)
if message:
broadcast(message, conn)
else:
remove(conn)
if not message:
break
def start_client():
sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
sock.bind((connect, conport))
sock.listen(1)
try:
while True:
conn, addr = sock.accept()
clients.append(conn)
start_new_thread(client_thread, (conn,))
finally:
sock.close()
def broadcast(message, connection):
for machine in clients:
if machine != connection:
try:
machine.sendall(message)
except:
machine.close()
remove(machine)
def remove(connection):
if connection in clients:
clients.remove(connection)
threading.Thread(target=start_client).start()