为什么python会将此消息附加到List中的每个Object?

时间:2017-01-07 08:38:30

标签: python list sockets oop chat

我正在尝试编写一个简单的聊天程序,但似乎无法解决的问题出现了。(我甚至无法找到原点)

让我们说我们有2个聊天室,并且被称为" chatA"和" chatB"并且每个聊天室中都有一个用户(" BOB"在" chatA"" PETE"在" chatB")他们是写作,即使是唯一使用他们的聊天室的人。 为什么接收其他人写的每条消息,即使它们在不同的聊天室中?

服务器代码:

import socket
from thread import start_new_thread

clientNameList = []
clientList = []
roomNameList = []
roomList = []

class Client(object):
    def __init__(self, username, room="none"):
        self.username = username
        self.room = room

class Room(object):
    def __init__(self, name, maxNumber, adminUser, userList=[], messageList=[]):
        self.name = name
        self.maxNumber = maxNumber
        self.adminUser = adminUser
        self.userList = userList
        self.messageList = messageList

def main():
    host = ''
    port = 12

    s = socket.socket()

    s.bind((host, port))

    s.listen(5)

    while True:
        c, (clientIp, clientPort) = s.accept()
        start_new_thread(newClient, (c,))
    s.close()
def newClient(c):
    username = c.recv(32)
    if username not in clientNameList:
        clientNameList.append(username)
        clientList.append(Client(username))
        c.send("SUCCE welcome, '%s'" %str(username))
        print username," connected!"
        start_new_thread(clientRecv, (c, username,))
        start_new_thread(clientSend, (c, username,))
    else:
        c.send("ERROR username already taken")
def clientRecv(c, username):
    running = True
    while running:
        try:
            message = c.recv(1024)
        except:
            clientIndex = clientNameList.index(username)
            activeRoom = clientList[clientIndex].room
            activeRoomIndex = roomNameList.index(activeRoom)
            roomList[activeRoomIndex].userList.remove(username)
            roomList[activeRoomIndex].messageList.append("%s left" %str(username))
            del clientList[clientIndex]
            clientNameList.remove(username)
            running = False
        if message[:5] == "/help":
            c.send("/help = this;\n/join 'room' = join room;\n/quit = quit\n/create 'roomname','max. num of Clients' = create room\n/users = display users(if not in a room, display all)\n/rooms = display chatrooms")
        elif message[:5] == "/join":
            if message[6:] not in roomNameList:
                c.send("ERROR room doesn't exist")
            else:
                clientIndex = clientNameList.index(username)
                newRoom = message[6:]
                newRoomIndex = roomNameList.index(newRoom)
                if roomList[newRoomIndex].maxNumber == len(roomList[newRoomIndex].userList):
                    activeRoom = clientList[clientIndex].room
                    c.send("ERROR '%s' is full" %str(activeRoom))
                else:
                    if clientList[clientIndex].room != "none":
                        clientIndex = clientNameList.index(username)
                        activeRoom = clientList[clientIndex].room
                        activeRoomIndex = roomNameList.index(activeRoom)
                        activeRoomUserIndex = roomList[activeRoomIndex].userList.index(username)
                        del roomList[activeRoomIndex].userList[activeRoomUserIndex]
                        roomList[activeRoomIndex].messageList.append("%s left the chatroom" %str(username))
                        c.send("SUCCE you left '%s'" %str(activeRoom))
                    roomList[newRoomIndex].userList.append(username)
                    roomList[newRoomIndex].messageList.append("%s joined" %str(username))
                    c.send("SUCCE you joined '%s'" %str(newRoom))
                    clientList[clientIndex].room = newRoom
        elif message[:5] == "/quit":
            c.send("SUCCE bye")
            clientIndex = clientNameList.index(username)
            activeRoom = clientList[clientIndex].room
            if activeRoom != "none":
                activeRoomIndex = roomNameList.index(activeRoom)
                roomList[activeRoomIndex].userList.remove(username)
                roomList[activeRoomIndex].messageList.append("%s left" %str(username))
            del clientList[clientIndex]
            clientNameList.remove(username)
            running = False
        elif message[:7] == "/create":
            arguments = message[8:].split(",")
            if len(arguments) != 2:
                c.send("ERROR syntax")
            else:
                if arguments[0] in roomNameList:
                    c.send("ERROR room already exist")
                else:
                    roomNameList.append(arguments[0])
                    try:
                        roomList.append(Room(arguments[0], int(arguments[1]), username))
                        c.send("SUCCE room '%s' created" %str(arguments[0]))
                    except:
                        c.send("ERROR syntax")
        elif message[:6] == "/users":
            if clientList[clientNameList.index(username)].room == "none":
                print "%s used /users on ALL" %str(username)
                for user in clientNameList:
                    c.send(user)
            else:
                print "%s used /users on %s" %(str(username), str(clientList[clientNameList.index(username)].room))
                for user in roomList[roomNameList.index(clientList[clientNameList.index(username)].room)].userList:
                    c.send(user)
        elif message[:6] == "/rooms":
            for room in roomNameList:
                c.send(room)
        elif message[:4] == "/mod":
            if len(message) < 6:
                c.send("ERROR not enough arguments")
            else:
                if clientList[clientNameList.index(username)].room != "none":
                    if roomList[roomNameList.index(clientList[clientNameList.index(username)].room)].adminUser != username:
                        c.send("ERROR you are not the room-admin")
                    else:
                        try:
                            newValue = int(message[5:])
                            roomList[roomNameList.index(clientList[clientNameList.index(username)].room)].maxNumber = newValue
                            c.send("SUCCE updated")
                        except:
                            c.send("ERROR invalid value")
                else:
                    c.send("ERROR you have to be inside a room to modify it")
        elif message[:6] == "/print":
            for message in roomList[int(message[7:])].messageList:
                print message
        else:
            if clientList[clientNameList.index(username)].room == "none":
                c.send("ERROR you are not in a chatroom")
            else:
                roomList[roomNameList.index(clientList[clientNameList.index(username)].room)].messageList.append("%s: %s" %(username, message))
def clientSend(c, username):
    last = 0
    running = True
    while running:
        try:
            clientIndex = clientNameList.index(username)
            if clientList[clientIndex].room != "none":
                activeRoom = clientList[clientIndex].room
                activeRoomIndex = roomNameList.index(activeRoom)
                messageCount = len(roomList[activeRoomIndex].messageList)-1
                if messageCount != last:
                    if messageCount - last > 1:
                        c.send("SUCCE %s %s\n" %(str(activeRoom),str(roomList[activeRoomIndex].messageList[last+1])))
                        last +=1
                    else:
                        c.send("SUCCE %s %s" %(str(activeRoom),str(roomList[activeRoomIndex].messageList[last+1])))
                        last +=1
        except:
            running = False
main()

客户代码:

import socket
from thread import start_new_thread
import time
import os

def main():
    host = raw_input("IP ->")
    port = 12

    s = socket.socket()
    s.connect((host, port))


    userinput = raw_input("username ->")
    s.send(userinput)
    print s.recv(128)

    time.sleep(1)
    os.system("cls")

    start_new_thread(sender, (s,))
    receiver(s)

def receiver(s):
    running = True
    while running:
        servermessage = s.recv(256)
        print "[>>]",servermessage
        if servermessage == "SUCCE bye":
            running = False

def sender(s):
    running = True
    while running:
        userinput = raw_input()
        if userinput == "/quit":
            running = False
        s.send(userinput)
main()

(我添加了一个命令(/ print x)用于调试目的,它证明每条消息都被附加到roomList中每个对象的每个messageList上)

为什么会这样,我怎么能改进我的代码?谢谢:))

0 个答案:

没有答案