一. 目的

  • 多个TCP客户端同时接入
  • 任一客户端数据的群发功能

二. 示例程序

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
import socket as sk
import multiprocessing as mp
import os

port = 2333 #TCP服务端端口

def Mass(sock_in, addr,sock_list): #定义群发函数
for sock_c in sock_list.items():
True
while True:
try:
readdata = sock_in.recv(1024)
if readdata:
print(readdata.decode('utf-8')) #将需要群发的数据打印出来
client = sock_list.copy()
del client[addr]
for sock_c in client.items():
try:
sock_c[1].send(readdata)
except:
del sock_list[sock_c[0]]
else:
for sock_c in sock_list.items():
if sock_c[0]!=addr:
True
del sock_list[addr]
os._exit(0)
break
except:
for sock_c in sock_list.items():
if sock_c[0]!=addr:
True
del sock_list[addr]
os._exit(0)
break

def main():
s = sk.socket(sk.AF_INET ,sk.SOCK_STREAM)
s.setsockopt(sk.SOL_SOCKET, sk.SO_KEEPALIVE, 1)
s.setsockopt(sk.SOL_TCP, sk.TCP_KEEPIDLE, 1)
s.setsockopt(sk.SOL_TCP, sk.TCP_KEEPINTVL, 1)
s.setsockopt(sk.SOL_TCP, sk.TCP_KEEPCNT, 1)
s.bind(('',port))
s.listen()
sock_list=mp.Manager().dict()
while True:
sock_in,addr = s.accept()
sock_list[addr]=sock_in
t1 = mp.Process(target=Mass, args=(sock_in, addr,sock_list))
t1.start()

if __name__ == '__main__':
main()

三. 注意事项

1.修改服务端口

1
port = 2333

2.需要用到的库

1
2
3
import socket as sk
import multiprocessing as mp
import os

四. 演示

在这里插入图片描述