python - 套接字不返回任何客户端
问题描述
我正在尝试构建一个套接字,并且我想打印一个客户端对象,但是由于某种原因,每当我连接它时它只会返回空{}
我是 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()
解决方案
推荐阅读
- jenkins - 中止的詹金斯管道作业继续运行后期
- java - 通过 getter 和 setter 更新 pojo 的通用方法
- android - 无法在 android studio 中解析 default_web_client_id
- python - 加深对 Python read() 和 open() 函数的理解
- javascript - 在 React 中动态更新“状态”会覆盖整个状态
- angular - 填充数组并使其可使用 Angular Material 过滤
- java - Android OneSignal 通知无法打开“已关闭”应用程序
- android - 如何在 Android 应用程序中为服务器提供回调 url
- r - 在R中使用多个条件左连接
- emacs - 更改 Spacemacs/Emacs 当前行号的颜色