#!/usr/bin/python
#coding:utf-8

import sys,os,socket
import tw,ws

client = []

class Server(tw.Protocol):
    #有客户端接入
    def connectionMade(self):
        self.attr={} #主要保存客户端的连接类型
        self.socketLeftString = '' #socket传输中需要粘包的数据
        self.transport.getHandle().setsockopt(socket.SOL_SOCKET, socket.SO_SNDBUF,32*1024)
        client.append( self )

    #有客户端断开
    def connectionLost(self,reason):
        if self in client:
            client.remove(self)
        
        print 'connectionLost'

    #收到客户端发来数据
    def dataReceived(self, msg):
        #WS握手
        if msg.lower().find('upgrade: websocket') != -1:
            ws.shake(self,msg)
            return
        ws.parse_recv_data(self,msg,self._dataReceived)
    
    #数据解压后，执行解包粘包操作
    def _dataReceived (self,msg):
        if msg=='ping':
            self.send('pong')

        elif msg.startswith('sendOther@_@'):
            msg = msg.replace('sendOther@_@','')
            
            for c in client:
                if c == self:
                    continue
                c.send( msg )

    
    def send (self,msg,callback=None):
        msg = str(msg)
        msg = ws.send_data(self,msg)
        return self.sendDo(msg,callback)

    def sendDo(self,msg,callback=None):
        if not self.transport.connected or msg is None:
            return
        msg = str(msg)
        tw.reactor.callFromThread(self.transport.write,msg)

#启动服务器
if __name__=='__main__':
    f = tw.Factory()
    f.protocol = Server
    tw.reactor.listenTCP(3000,f)
    print 'starting 3000'
    tw.reactor.run()
