Python3 socket 实现即时通讯脚本,threading 多线程
------------------------------------------------服务端代码--------------------------------------
__author__ = "托尼老师" """ 即时通讯原理 @@@ 服务端代码 """ from socket import * import threading ip = ‘0.0.0.0‘ port =8888 # 定义 socket 参数 Server = socket(AF_INET,SOCK_STREAM) Server.bind((ip,port)) Server.listen() print("[*] SocketServer 正在监听...") # 接受函数 def recvs(): while 1: print(‘ [*] 客户端说: %s ‘% client.recv(1024).decode(‘utf-8‘)) #发送函数 def sends(): while 1: say = bytes(input(‘ [*] 我说: ‘) , encoding=‘utf-8‘) client.send(say) # 堵塞接受请求 client,client_ip = Server.accept() print(client_ip[0] +‘:‘+str(client_ip[1])+‘ 连接成功!‘ ) # 创建接受线程 receive = threading.Thread(target =recvs ,args=() ) receive.start() # 创建发送线程 send = threading.Thread(target =sends ,args=() ) send.start()
------------------------------------------------客户端代码--------------------------------------
__author__ = "托尼老师" """ 即时通讯原理 @@@ 客户端代码 """ from socket import * import threading ip,port =‘127.0.0.1‘,8888 Client = socket(AF_INET,SOCK_STREAM) Client.connect((ip,port)) def sends() -> ‘发送函数‘: while 1: say = bytes(input("[*]我说: "),encoding=‘utf-8‘) Client.send(say) def recvs() -> ‘接受函数‘: while 1: print(‘[*] 服务端说: %s ‘ % Client.recv(1024).decode(‘utf-8‘)) receive = threading.Thread(target =recvs ,args=() ) receive.start() # 创建发送线程 send = threading.Thread(target =sends ,args=() ) send.start()
先执行 服务端代码,再执行客户端代码,可以实现基本通讯功能。仅供参考!欢迎指出优化!
相关推荐
LczPtr 2020-05-09
一叶梧桐 2020-10-14
lzzyok 2020-10-10
digwtx 2020-09-14
efeve 2020-09-14
poplpsure 2020-08-17
ITxiaobaibai 2020-07-26
libowenhit 2020-07-23
luckykapok 2020-07-06
hongsheyoumo 2020-06-27
jannal 2020-06-21
lanmantech 2020-06-16
咻咻ing 2020-06-16
weibingbingnet 2020-06-14
woyanyouxin 2020-06-04
houjinkai 2020-06-03
txj 2020-06-02
Chydar 2020-05-15