小程序利用TCPSOCKET和后端的python文件进行连接,小程序在TCPSOCKET多次重新连接后,监听函数也会随之多次觸发回调函数,要怎么解决这种状况?
js代码
const app = getApp()
const tcp = wx.createTCPSocket()
Page({
data: {
UMsg:'',
SMsg:'',
ConntectStatus:'closed',
},
connectgo:function(){
if(this.data.ConntectStatus=='closed'){
tcp.connect({
address:'localhost',
port:8080
})
tcp.onClose(this.ifclose)
tcp.onConnect(this.ifconnect)
tcp.onMessage(this.ifmesggage)
}
else{
wx.showToast({
title: 'Is Connect',
icon: 'error',
})
}
},
connectclose:function(res){
if(this.data.ConntectStatus=='connected'){
tcp.close()
}
else{
wx.showToast({
title: 'No Connect',
icon:'error',
})
}
},
UMsgput:function(res){
if(this.data.ConntectStatus=='connected'){
this.setData({
UMsg:res.detail.value
})
tcp.write(this.data.UMsg)
console.log('User Send message: ',this.data.UMsg)
}
else{
wx.showToast({
title: 'No Connect',
icon: 'error',
})
}
},
ifconnect:function(){
console.log('connect success')
this.setData({
ConntectStatus:'connected'
})
},
ifmesggage:function(res){
let unit8Arr = new Uint8Array(res.message) ;
let encodedString = String.fromCharCode.apply(null, unit8Arr),
decodedString = decodeURIComponent(escape((encodedString)));//没有这一步中文会乱码
console.log('Server send back message: ',decodedString);
this.setData({
SMsg:decodedString
})
},
ifclose:function(res){
console.log('close connect')
this.setData({
ConntectStatus:'closed'
})
tcp.offClose(this.ifclose)
tcp.offConnect(this.ifconnect)
tcp.offMessage(this.ifmesggage)
},
})
py代码
import imp
import socket
def main():
#创建套接字
tcp_server=socket.socket(socket.AF_INET,socket.SOCK_STREAM)
# 绑定本地信息
tcp_server.bind(('0.0.0.0',8080))
# 套接字主动变被动 listen)
tcp_server.listen(128)
while True: #循环为多个客户端服务
print('*****等待新的客户到来*****')
# accept产生新的套接字
new_client_socket,client_addr=tcp_server.accept() # accept返回元组
#**************************************************************以下为具体服务流程
print('新的客户已经到来')
# 等待
print(client_addr)
while True: #循环为一个客户端服务多次
# 接受客户请求
recv_data=new_client_socket.recv(1024)
# 如果recv解堵塞,要么客户端发送数据,要么客户端关闭调用close
if recv_data:
print("客户端发来的请求是:%s" % recv_data.decode('gbk'))
# 回送信息给客户端
send_msg = recv_data.decode('gbk')
new_client_socket.sendall(send_msg.encode('gbk'))
print("回送信息给客户端:", recv_data.decode('gbk'))
else:
print("此客户端关闭")
break
#***************************************************个性化服务结束
# 关闭accept返回的套接字,不会在为这个客户服务
new_client_socket.close()
print("————————已经服务完毕————————")
# 监听套接字关闭会导致不能再次等待新客户到来
tcp_server.close
if __name__ =="__main__":\
main()