如何获得到一台服务器的多个客户端连接?

时间:2019-01-08 23:47:11

标签: python-3.x windows sockets server

我希望有多个客户端连接到一台服务器,并且能够在不互相干扰的情况下进行通信。

客户端代码(在此原型中无需更改,仅在需要时更改):

import socket
host = "X.X.X.X"
port = 8008

def Main(s, i):
    if i == 1:
        data = s.recv(1024).decode("utf-8")
        print(data)
        i = 0
    message = input("-> ")
    if " " in message:
        [task, info] = message.split(" ")
    else:
        task = message
    task = task.lower()
    if task == "exit":
        exit()
    elif task.startswith("echo"):
        s.send(message.encode("utf-8"))
        data = s.recv(1024).decode("utf-8")
        print(data)
    else:
        print("Incorrect input!")
    Main(s, 0)


def connect():
    s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
    s.connect((host, port))
    Main(s, 1)


if __name__ == '__main__':
    s = connect()



服务器代码(仅用于单个客户端连接的简化原型):

import socket
import time

host = "X.X.X.X"
port = 8008

s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.bind((host,port))


def connect():
    s.listen(5)
    c, address = s.accept()
    print("Connected to " + str(address) + "!")
    return c, address


def Main(i, c, address):
    try:
        if i == 1:
            message = ("Server: Hello " + host + " pleased to meet you.")
            c.send(message.encode("utf-8"))
            del message
        while True:
            message = c.recv(1024).decode("utf-8")
            if not message:
                break
            elif " " in message:
                [task, info] = message.split(" ")
            else:
                task = message

            if task == "echo":
                c.send(info.encode("utf-8"))
                del info
        Main(0, c, address)
    except:
            print("Timed out from " + str(address) + "!")
            [c, address] = connect()
            Main(1, c, address)


if __name__ == "__main__":
    [c, address] = connect()
    Main(1, c, address)
    while 1:
        Main(0, c, address)
        time.sleep(0.9997)


我想要的是通常的普通服务器类型:
-我希望服务器每秒刷新一次。在那儿,搜索传入的连接并接受它们。
-我还希望它能够搜索是否有任何客户端断开连接并删除它的ip,以免引起进一步的问题。

0 个答案:

没有答案