python创建socket连接和父子进程
简介:解决python的socket中长连接数据调用的问题。
#!/usr/bin/python3
# -*- coding: utf-8 -*-
from socketclusterclient import Socketcluster
import logging
import time
import _thread
logging.basicConfig(format='%(levelname)s:%(message)s', level=logging.DEBUG)
var_time = 0;
def onconnect(socket):
logging.info("on connect got called")
def ondisconnect(socket):
logging.info("on disconnect got called")
def onConnectError(socket, error):
logging.info("On connect error got called")
def onSetAuthentication(socket, token):
logging.info("Token received " + token)
socket.setAuthtoken(token)
def onAuthentication(socket, isauthenticated):
logging.info("Authenticated is " + str(isauthenticated))
socket.subscribe("global")
socket.onchannel('global', message)
def message(key, object):
#print ("Got data " + str(object) + " from key " +key)
global var_time
var_time = time.time()
#print("------"+str(var_time))
def read_time():
while(True):
#print('{now:'+ str(time.time())+'}, var:'+str(var_time)+'}')
#time.sleep(10)
f = open('/etc/wxb.txt','w')
diff = int(time.time()) - int(var_time)
f.write(str(diff))
f.close
time.sleep(10)
if __name__ == "__main__":
print('start read time....')
_thread.start_new_thread(read_time, ())
print('start socket ....')
socket = Socketcluster.socket("ws://localhost:1472/socketcluster/")
socket.setBasicListener(onconnect, ondisconnect, onConnectError)
socket.setAuthenticationListener(onSetAuthentication, onAuthentication)
#socket.enablelogger(True)
while True:
socket.connect()