老实说,我不知道为什么会这样,我想由于它不在堆栈交换中,所以我错了一个n00by错误。所以这是错误:

s = socket.socket(socket.AF_INET,socket.SOCK_STREAM)
UnboundLocalError:在分配
之前引用了本地变量'socket'

tcpServer.py

import socket

def Main():
    UID = 1001
    sockets = []
    users = [] ## create usernames list
    sessionLimit = input("session Queue Limit: ")

    s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
    s.bind(('192.168.1.74', 12127))

    s.listen(sessionLimit) ## listen for 1 connection at a time

    while True:
        c, addr = s.accept()
        sockets.append(c)
        users.append(c.recv(1024).decode('utf-8'))
        print("Connection from " + str(addr))

        data = c.recv(1024).decode('utf-8') ## recieve 1024 bytes from client at a time, and then decode it into utf-8
        if not data:
            break

        temp == data
        temp.split(" ")
        if temp[0] == "//": ## check to see if user has sent command
            if temp[1] == "msg":
                for i in range(len(users)):
                    if users[i] == temp[2]:
                        sockets[i].send((" ".join(temp[::2])).encode('utf-8'))
        else: ## else, send data to all users. Could just use s.sendall(data.encode('utf-8'))
            for socket in sockets:
                socket.send(data.encode('utf-8')) ## send to sockets[socket]

        ##print("From connected user: " + data)
        ##data = data.upper()
        ##print("Sending: " + data)
        ##c.send(data.encode('utf-8'))

        ## command listening
        commands = input("-> ")
        commands.split(" ")

        if commands[0] == "exit":
            c.close() ## close connection
        elif commands[0] == "/msg":
            for i in range(len(users)):
                if users[i] == commands[1]:
                    sockets[i].send((" ".join(commands[::1])).encode('utf-8'))
    """
       elif commands[0] == "/rename": ## dont implement yet, due to users[] length changing
            for i in range(len(users)):
                if users[i] == commands[1]:
                    sockets[i].send("<server_" + UID + "> rename " + commands[2].encode('utf-8'))
        """
    c.close()

    if __name__ == "__main__":
        Main()

谢谢你的帮助 !
-雅各布

最佳答案

问题是,当您执行以下代码块时,您正在socket函数的上下文中使用变量名称Main():

    for socket in sockets:
        socket.send(data.encode('utf-8')) ## send to sockets[socket]

这导致了socket库的命名问题。如果将其更改为:
    for sock in sockets:
        sock.send(data.encode('utf-8')) ## send to sockets[socket]

它将开始工作。我还必须以不同的方式缩进代码,以确保所有代码都已设置在Main()函数中,并且还必须确保input()解析为int。供引用,这是为我工作的完整代码块:
import socket

def Main():
    UID = 1001
    sockets = []
    users = [] ## create usernames list
    sessionLimit = int(input("session Queue Limit: "))

    s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
    s.bind(('192.168.1.74', 12127))
    s.listen(sessionLimit) ## listen for 1 connection at a time

    while True:
        c, addr = s.accept()
        sockets.append(c)
        users.append(c.recv(1024).decode('utf-8'))
        print("Connection from " + str(addr))

        data = c.recv(1024).decode('utf-8') ## recieve 1024 bytes from client at a time, and then decode it into utf-8
        if not data:
            break

        temp == data
        temp.split(" ")
        if temp[0] == "//": ## check to see if user has sent command
            if temp[1] == "msg":
                for i in range(len(users)):
                    if users[i] == temp[2]:
                        sockets[i].send((" ".join(temp[::2])).encode('utf-8'))
        else: ## else, send data to all users. Could just use s.sendall(data.encode('utf-8'))
            for sock in sockets:
                sock.send(data.encode('utf-8')) ## send to sockets[socket]

        ##print("From connected user: " + data)
        ##data = data.upper()
        ##print("Sending: " + data)
        ##c.send(data.encode('utf-8'))

        ## command listening
        commands = input("-> ")
        commands.split(" ")

        if commands[0] == "exit":
            c.close() ## close connection
        elif commands[0] == "/msg":
            for i in range(len(users)):
                if users[i] == commands[1]:
                    sockets[i].send((" ".join(commands[::1])).encode('utf-8'))
        """
        elif commands[0] == "/rename": ## dont implement yet, due to users[] length changing
            for i in range(len(users)):
                if users[i] == commands[1]:
                    sockets[i].send("<server_" + UID + "> rename " + commands[2].encode('utf-8'))
        """
    c.close()

if __name__ == "__main__":
    Main()

关于python - Python导入了模块,但是在启动它时无法识别它?,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/34667024/

10-11 22:43
查看更多