标签:enc thread 定义 nec 即时通 while NPU start bytes
------------------------------------------------服务端代码--------------------------------------__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()
先执行 服务端代码,再执行客户端代码,可以实现基本通讯功能。仅供参考!欢迎指出优化!
Python3 socket 实现即时通讯脚本,threading 多线程
标签:enc thread 定义 nec 即时通 while NPU start bytes
原文地址:https://blog.51cto.com/13876557/2499449