Python多TCP客户端数据透传服务端

  • Post author:
  • Post category:python




一. 目的

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



二. 示例程序

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)
            breakdef 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.修改服务端口

port = 2333

 
 

2.需要用到的库

import socket as sk
import multiprocessing as mp
import os

 
 



四. 演示

在这里插入图片描述