首页 > 解决方案 > 套接字不返回任何客户端

问题描述

我正在尝试构建一个套接字,并且我想打印一个客户端对象,但是由于某种原因,每当我连接它时它只会返回空{}

我是 Python 新手,想要一些见解

import socket
from threading import Thread
from multiprocessing import Process
import time as t

previousTime = t.time()

clients = {}

hostAddr = "127.0.0.1"
hostPort = 80

class sClient(Thread):
    def __init__(self, socket, address):
        Thread.__init__(self)
        self.sock = socket
        self.addr = address
        self.start()

    def run(self):
        print("\nClient Connected from {}!".format(self.addr[0]))
        self.sock.sendall("Welcome master".encode())

class sHost():
    def __init__(self, host, port, clients):
        self.sHost = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
        self.sHost.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
        self.sHost.bind((host, port))
        self.sHost.listen()
        self.start_listening()

    def start_listening(self):
        while 1:
            clientSocket, clientAddr = self.sHost.accept()
            clients[clientSocket.fileno()] = clientSocket

            sClient(clientSocket, clientAddr)

def SendMsgToAllClients(msg):
    print(clients) # this is empty
    for client in clients.values():
        try:
            client.sendall(msg.encode())
        except Exception as e:
            print("Client probably disconnected, removing...")
        finally:
            del clients[client.fileno()]

if __name__ == '__main__':
    Process(target=sHost, args=(hostAddr, hostPort, clients)).start()
    print("Server is running")

    while 1:
        if previousTime + 3 <= t.time():
            SendMsgToAllClients("Test")
            previousTime = t.time()

标签: python

解决方案


推荐阅读