python多客户端服务器

时间:2018-07-19 15:28:32

标签: python multithreading sockets

我通过多线程模块编写了一个客户端和服务器程序,但是代码有问题

考虑以下输出:(客户端超过2个(这是示例))

+---------+--------------+--------+
| [Index] | [IP-Address] | [Port] |
+---------+--------------+--------+
|    0    | 192.168.1.12 | 34224  |
|    1    | 192.168.1.10 | 39870  |
+---------+--------------+--------+

我希望服务器在用户输入“ choose [number]”命令(例如选择0 1)时将相应的命令发送给客户端

如果用户发送错误的号码,例如:

chose 2 3
chose 0 2
chose 2 0
chose
chose 0 (just one number)

服务器显示无效选择

我的输出:

+---------+--------------+--------+
| [Index] | [IP-Address] | [Port] |
+---------+--------------+--------+
|    0    | 192.168.1.12 | 34232  |
|    1    | 192.168.1.10 | 40032  |
+---------+--------------+--------+
[BAT]> chose    
[ERROR] Chose more than one!
[BAT]> chose 2 3
[WARNING] Not valid selection
[WARNING] Not valid selection
[BAT]> chose 
[ERROR] Chose more than one!
[BAT]> chose 0  
[ERROR] Chose more than one!
[BAT]> chose 0 1
[Multicasting-CMD]> mkdir test2
[STATUS] Success
[Multicasting-CMD]> 
[WARNING] Command is empty!
[BAT]> 
[WARNING] Command is empty!

我的代码:

if "chose" in COMMAND:
    Multicasting_check()


def Multicasting_check(COMMAND):
    Target_list = COMMAND.replace("chose ", "")
    Target_list = Target_list.split()

    checking_list = []

    if len(Target_list) > 1:

        for conn_item in ALL_CONNECTIONS:
            checking_list.append(ALL_CONNECTIONS.index(conn_item))

        for Items in Target_list:
            Int_items = int(Items)

            if Int_items in checking_list:
                Multicasting(Int_items)
            else:
                print "[WARNING] Not valid selection"
                continue
    else:
        print "[ERROR] Chose more than one!"




def Multicasting(Conn_number):
    Message = raw_input("[Multicasting-CMD]> ")

    if len(Message) > 0:
        if Message == "quit":
            BAT()

        try:
            ALL_CONNECTIONS[Conn_number].send(str.encode(Message))
            print colored("[STATUS]", "blue"), colored("Success", "green")
        except socket.error:
            print "[ERROR] Connection was lost with", ALL_HOST_ADDRESSES[Conn_number][0]
    else:
        print "[WARNING] Command is empty!"

所有客户端无法执行命令 我该如何解决?

谢谢大家

0 个答案:

没有答案