我正在编写这个简单的多线程套接字程序,它检查数据库中是否存在用户名和密码。 Client.py
import socket
import getpass
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.connect(("127.0.0.1", 1234))
while True:
command = input(">>")
case = command.split()
if case[0] == "bye":
s.sendall(bytes("close", "utf-8"))
break
elif case[0] == "login":
psswrd = getpass.getpass()
s.sendall(bytes("login" + " " + case[1] + " " + psswrd, "utf-8"))
rep = s.recv(2048).decode("utf-8")
print(rep)
else:
print("Wrong command")
s.close()
Server.py
import socket
import threading
from user import User
class ClientThread(threading.Thread):
def __init__(self, addr, client):
threading.Thread.__init__(self)
self.client = client
print(f" {addr} connected")
def run(self):
while True:
try:
msg = client.recv(2048).decode("utf-8")
data = msg.split()
if data[0] == "close":
client.close()
break
elif data[0] == "login":
u = User(data[1], data[2])
result = u.find_user() //checks if it exists in dtb
if result and u.pwd == result[2]:
client.sendall(bytes("Login successfully", "utf-8"))
else:
client.sendall(bytes("Wrong", "utf-8"))
except:
break
print(f"{addr} closed")
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.bind(('127.0.0.1', 1234))
while True:
s.listen(1)
client, addr = s.accept()
newthread = ClientThread(addr, client)
newthread.start()
每个客户端应该单独行动,但当我尝试与2个客户端,在第一个客户端输入“再见”连接关闭两个连接,而“登录”将只运行为第二个客户端,第一个客户端将被卡住。如果有人能告诉我哪部分做错了,那就太好了 问题来源StackOverflow 地址:/questions/59466993/python-socket-closes-all-connection-instead-of-only-itself
版权声明:本文内容由阿里云实名注册用户自发贡献,版权归原作者所有,阿里云开发者社区不拥有其著作权,亦不承担相应法律责任。具体规则请查看《阿里云开发者社区用户服务协议》和《阿里云开发者社区知识产权保护指引》。如果您发现本社区中有涉嫌抄袭的内容,填写侵权投诉表单进行举报,一经查实,本社区将立刻删除涉嫌侵权内容。