开发者社区> 问答> 正文

Python套接字关闭所有连接,而不是只关闭它自己

我正在编写这个简单的多线程套接字程序,它检查数据库中是否存在用户名和密码。 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

展开
收起
kun坤 2019-12-25 09:35:53 398 0
0 条回答
写回答
取消 提交回答
问答排行榜
最热
最新

相关电子书

更多
From Python Scikit-Learn to Sc 立即下载
Data Pre-Processing in Python: 立即下载
双剑合璧-Python和大数据计算平台的结合 立即下载