python socket-tcp多人网络聊天室服务端(35行代码实现)
作者:互联网
关键词:多进程、TCP、共享内存
先放图:
先放代码,之后再描述细节
import socket as sk import multiprocessing as mp import time as t import os def c_s_c(sock_in, addr,sock_list): #进程出来函数 for sock_c in sock_list.items(): sock_c[1].send(("user"+str(addr)+"---in---\n").encode()) #遍历并发送给所有在聊天室的用户 while True: readdata = sock_in.recv(1024) if readdata: print(readdata) for sock_c in sock_list.items(): sock_c[1].send(str(addr).encode()+readdata) #转发给所用用户 else: for sock_c in sock_list.items(): sock_c[1].send(("user"+str(addr)+"---out---").encode()) del sock_list[addr] sock_in.close() os._exit(0) break def main(): s = sk.socket(sk.AF_INET ,sk.SOCK_STREAM) s.bind(('10.238.2.208',2333)) s.listen() sock_list=mp.Manager().dict() #共享内存字典-------------------------------- while True: sock,addr = s.accept() sock_list[addr]=sock #将地址作为索引-------------------------------- t1 = mp.Process(target=c_s_c, args=(sock, addr,sock_list)) #多进程------ t1.start() if __name__ == '__main__': main()
标签:__,socket,python,sock,list,tcp,---,readdata,addr 来源: https://www.cnblogs.com/hardfood/p/14263412.html