【问题标题】:How to make a kick feature in Python socket chat room?如何在 Python 套接字聊天室中进行踢球功能?
【发布时间】:2019-07-20 08:17:55
【问题描述】:

这是一个套接字聊天室,客户端可以在其中相互发送消息。我想要一个踢球功能,服务器可以踢出某些人。

我已经设法让它踢出所需的用户,但它仍然把我踢出,这是执行此操作的代码:

for name in keys:
    if('**kick '+name) in data:
        clients[name].close()
        del clients[name]
        found = True

我试过这个:

for name in keys:
    if('**kick '+name) in data:
        data = data.replace('**kick '+name,'')
        clients.get(name).pop
        found = True

但是当我运行这段代码并尝试它时,我反而被踢了。

这是我的完整代码:

服务器.py

import socket, threading
host = "127.0.0.1"
port = 4000
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.bind((host,port))
s.listen()
clients = {}
print("Server is ready...")
serverRunning = True
def handle_client(conn, uname):

    clientConnected = True
    keys = clients.keys()
    help = 'There are 3 commands in Messenger\n1**chatlist > gives you the list of the people currently online\n2**quit > To end your session and quit the server\n3**(username) sends a private message to any user you want'

    while clientConnected:
        try:
            response = 'Number of People Online\n'
            data = conn.recv(1024).decode('ascii')
            found = False
            if '**' not in data:
                for k,v in clients.items():
                    if v != conn:
                        v.send(data.encode('ascii'))
                        found = True


            elif '**chatlist' in data:
                clientNo = 0
                for name in keys:
                    clientNo += 1
                    response = response + str(clientNo) +'::' + name+'\n'
                conn.send(response.encode('ascii'))
                found = True


            elif '**help' in data:
                conn.send(help.encode('ascii'))
                found = True
            else:
                for name in keys:
                    if('**'+name) in data:
                        data = data.replace('**'+name,'')
                        clients.get(name).send(data.encode('ascii'))
                        found = True
                    if('**kick '+name) in data:
                        clients.get(name).pop
                        found = True
                if(not found):
                    conn.send('Trying to send message to invalid person.'.encode('ascii'))


        except:
            clients.pop(uname)
            print(uname + ' has logged out')
            clientConnected = False

while serverRunning:
    conn,addr = s.accept()
    uname = conn.recv(1024).decode('ascii')
    print('%s connected to the server'%str(uname))
    conn.send('Welcome to Messenger. Type **help to know all the commands'.encode('ascii'))

    if(conn not in clients):
        clients[uname] = conn
        threading.Thread(target = handle_client, args = (conn, uname,)).start()

客户端.py

import socket,threading
host = "127.0.0.1"
port = 4000
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.connect((host,port))
uname = input("Enter username: ")
s.send(uname.encode('ascii'))
clientRunning = True

def echo_data(sock):
   serverDown = False
   while clientRunning and (not serverDown):
      try:
         data = sock.recv(1024).decode('ascii')
         print(data)
      except:
         print('Server is Down. You are now Disconnected. Press enter to exit...')
         serverDown = True


threading.Thread(target=echo_data, args = (s,)).start()
while clientRunning:
   tempMsg = input()
   data = uname + '>> ' + tempMsg
   s.send(data.encode('ascii'))

【问题讨论】:

    标签: python python-3.x sockets tcp peer


    【解决方案1】:

    clients 是一个字典。所以基本上,踢特定用户意味着从客户字典中删除他的凭据。所以而不是 clients.get(name).pop
    采用 clients.pop(name)

    编辑:也不要使用for name in keys: 使用for name in list(clients): 因为,您不能在迭代字典时更改字典的大小。它会抛出异常。但是,此代码只会将用户从字典中删除,而不会将您踢出。除非您确实从字典中获取用户的值并使用 .close(),否则用户不会被踢出。希望这会有所帮助

    【讨论】:

    • 您在尝试将用户踢出聊天时遇到异常。发生这种情况是因为在您遍历字典时,您无法更改它的大小。请参阅编辑后的答案
    • 我将如何使用.close()
    【解决方案2】:

    您可以使用del 代替.pop

    注释clients.get(name).pop 代码并改写del clients[name]

    您需要从 except 块中删除 clients.pop(uname)。就是这样。

    这里是代码

    server.py

    import socket, threading
    host = "127.0.0.1"
    port = 5000
    s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
    s.bind((host,port))
    s.listen()
    clients = {}
    print("Server is ready...")
    serverRunning = True
    def handle_client(conn, uname):
    
        clientConnected = True
        keys = clients.keys()
        help = 'There are 3 commands in Messenger\n1**chatlist > gives you the list of the people currently online\n2**quit > To end your session and quit the server\n3**(username) sends a private message to any user you want'
    
        while clientConnected:
            try:
                response = 'Number of People Online\n'
                data = conn.recv(1024).decode('ascii')
                found = False
                if '**' not in data:
                    for k,v in clients.items():
                        if v != conn:
                            v.send(data.encode('ascii'))
                            found = True
    
    
                elif '**chatlist' in data:
                    clientNo = 0
                    for name in keys:
                        clientNo += 1
                        response = response + str(clientNo) +'::' + name+'\n'
                    conn.send(response.encode('ascii'))
                    found = True
    
    
                elif '**help' in data:
                    conn.send(help.encode('ascii'))
                    found = True
                else:
                    for name in keys:
                        if('**'+name) in data:
                            data = data.replace('**'+name,'')
                            clients.get(name).send(data.encode('ascii'))
                            found = True
                        if('**kick '+name) in data:
                            print('Name: '+ name)
                            print('Client: '+ str(clients))
                            # clients.get(name).pop
                            del clients[name]
                            found = True
                    if(not found):
                        conn.send('Trying to send message to invalid person.'.encode('ascii'))
    
    
            except:
                print(uname + ' has logged out')
                clientConnected = False
    
    while serverRunning:
        conn,addr = s.accept()
        uname = conn.recv(1024).decode('ascii')
        print('User : '+ uname)
        print('%s connected to the server'%str(uname))
        conn.send('Welcome to Messenger. Type **help to know all the commands'.encode('ascii'))
    
        if(conn not in clients):
            print("Conn: " + str(conn))
            clients[uname] = conn
            threading.Thread(target = handle_client, args = (conn, uname,)).start()
    

    客户端.py

    #!/usr/bin/env python3
    
    import socket,threading
    host = "127.0.0.1"
    port = 5000
    s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
    s.connect((host,port))
    # uname = raw_input("Enter username: ")
    uname = input("Enter username: ")
    print('Uname: '+ str(uname))
    s.send(uname.encode('ascii'))
    clientRunning = True
    
    def echo_data(sock):
       serverDown = False
       while clientRunning and (not serverDown):
          try:
             data = sock.recv(1024).decode('ascii')
             print(data)
          except:
             print('Server is Down. You are now Disconnected. Press enter to exit...')
             serverDown = True
    
    
    threading.Thread(target=echo_data, args = (s,)).start()
    while clientRunning:
       tempMsg = input()
       data = uname + '>> ' + tempMsg
       s.send(data.encode('ascii'))
    

    【讨论】:

    • 出于某种原因它仍然把我踢出聊天:(
    • 我在我的机器上测试了你的代码,它工作正常。你的代码和上面的不一样吗?
    • 这并没有什么不同,因为我复制了上面的代码并将其更改为您建议的内容,但它仍然在踢我:(
    • 你能给我正确的代码,以便我可以将它与我的比较,以便我更正它
    • 另外你用的是什么版本的python?
    【解决方案3】:

    我一直在制作一个聊天应用程序,对我来说,禁止某人的最佳方法是

    1. 制作数据库
    2. 为人们提供用户名、密码、数字 ID
    3. 每当有人连接时,都要求他们提供那里的凭据。(ID 可以是程序直接提供给您的东西,而用户可能不必提供)
    4. 如果想禁止某人使用数据库中的信息
    5. 如果在数据库中他被禁止,则关闭套接字。

    【讨论】:

      猜你喜欢
      • 2018-03-22
      • 2019-09-08
      • 2019-07-03
      • 2011-10-12
      • 1970-01-01
      • 1970-01-01
      • 2014-06-17
      • 1970-01-01
      • 2018-11-20
      相关资源
      最近更新 更多