Commit 53936aa9 by 熊付

【websocket】

1 parent b17c0900
...@@ -37,9 +37,11 @@ class Server (): ...@@ -37,9 +37,11 @@ class Server ():
self.stops = [] self.stops = []
self.h=h self.h=h
self.p=p self.p=p
self.subtask_id = None
# 监听客户端连接 # 监听客户端连接
def listen_client(self): def listen_client(self):
while 1: while 1:
time.sleep(200)
# 循环监听 # 循环监听
tcpClientSock, addr = self.sock.accept () tcpClientSock, addr = self.sock.accept ()
address = addr[0] + ':' + str ( addr[1] ) # ip:port address = addr[0] + ':' + str ( addr[1] ) # ip:port
...@@ -152,22 +154,34 @@ class Server (): ...@@ -152,22 +154,34 @@ class Server ():
# 开启线程记录 # 开启线程记录
if raw_str: if raw_str:
t1 = threading.Thread ( target=self.send_data, args=[raw_str, address] ) print type ( raw_str )
t1.start () try:
da = eval ( raw_str )
def send_data(self, data, address): if type ( da ) is dict:
if da.has_key ( 'subtask_id' ):
self.subtask_id = da['subtask_id']
except Exception as e:
print e
def send_data(self, str_data, address):
if type ( str_data ) is str:
data = json.loads ( str_data )
if type ( data ) is dict:
if data.has_key ( 'subtask_id' ):
subtask_id = data['subtask_id']
if self.subtask_id and self.subtask_id == subtask_id:
import struct import struct
from urllib import unquote from urllib import unquote
try: try:
username = unquote ( self.users[address] ) username = unquote ( self.users[address] )
except: except:
username = '匿名用户' username = '匿名用户'
#if data: # if data:
# data = str ( '【' + username + '说】' + data ) # data = str ( '【' + username + '说】' + data )
#else: # else:
# return False # return False
token = "\x81" token = "\x81"
length = len ( data ) length = len ( str_data )
if length < 126: if length < 126:
print '126' print '126'
token += struct.pack ( "B", length ) token += struct.pack ( "B", length )
...@@ -180,10 +194,10 @@ class Server (): ...@@ -180,10 +194,10 @@ class Server ():
print 'token=%s' % token print 'token=%s' % token
# struct为Python中处理二进制数的模块,二进制流为C,或网络流的形式。 # struct为Python中处理二进制数的模块,二进制流为C,或网络流的形式。
data = '%s%s' % (token, data) str_data = '%s%s' % (token, str_data)
print data print str_data
try: try:
#for key, val in self.clients.iteritems (): # for key, val in self.clients.iteritems ():
# print # print
# client = val # client = val
# try: # try:
...@@ -192,9 +206,15 @@ class Server (): ...@@ -192,9 +206,15 @@ class Server ():
# except: # except:
# self.close_client ( key ) # self.close_client ( key )
client = self.clients[address] client = self.clients[address]
client.send ( data ) client.send ( str_data )
except: except:
pass pass
else:
pass
else:
pass
else:
pass
def close_client(self, address): def close_client(self, address):
try: try:
......
Markdown is supported
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!