#!/usr/bin/env python
# -*- coding: utf-8 -*-
#创建SocketServerTCP服务器：
import SocketServer
from SocketServer import StreamRequestHandler as SRH
import ClientIOManger
import os
import socket
import QueueObjs
#import copy

def testPortUsed(pport):#9101
    strtmp = os.popen("lsof -i:%d"%(pport)) 
    print type(strtmp)
    cmdback = strtmp.readlines()
    print cmdback

myname = socket.getfqdn(socket.gethostname())
myaddr = socket.gethostbyname(myname)

print 'ip:%s'%(myaddr)
host = str("192.168.0.113")
#host = str("192.168.0.122")
#host = str("114.215.203.152")
port = 9101
addr = (host,port)

testPortUsed(9101)

SERVERDAT = ClientIOManger.ClientIOManger()
connectQueue = SERVERDAT.getConnectQueue()
mainThreadName = SERVERDAT.mainThreadName
connectThreadName = SERVERDAT.connectThreadName
class Servers(SRH):
    def handle(self):
        print 'got connection from ',self.client_address
        global connectQueue
        global mainThreadName
        global connectThreadName
        self.connectQueue = connectQueue
        while True:
            try:  
                data = self.request.recv(1024)
            except EOFError:  
                print '接收客户端错误，客户端已断开连接,错误码:' 
                print EOFError  
                break
            except:  
                print '接收客户端错误，客户端已断开连接'
                break
            if not data: 
                break
            print 'data len:%d'%(len(data))
            print "RECV from ", self.client_address
            clientconnectobj = QueueObjs.ClientConnectObj(data,self.client_address[0],self.request)
            queueobj = QueueObjs.QueueMangerObj(clientconnectobj,QueueObjs.Flog_ClientConnectObj,mainThreadName,connectThreadName)
            #self.connectQueue.put(copy.deepcopy(queueobj))
            self.connectQueue.put(queueobj)
            #self.serverDat.request(data,self.client_address[0],self.request)
print 'server is running....'
server = SocketServer.ThreadingTCPServer(addr,Servers,bind_and_activate = False)
server.allow_reuse_address = True   #设置IP地址和端口可以不使用客户端连接等待，并手动绑定服务器地址和端口，手动激活服务器,要不然每一次重启服务器都会出现端口占用的问题
server.server_bind()
server.server_activate()
server.serve_forever()