windows监听socket和标准输入

原来的代码

    def input_command(self):
        msg = raw_input('\nPlease input the command:')
        remote_id = raw_input("Please input remote id:")
        msg_send = "%s||%s" % (remote_id, msg)
        self.client_socket.send(msg_send)
        self.flag = 1
        #todo 这里输入完毕后socket会关闭,找到原因后写到博客园上

    def socket_handler(self):
        while 1:
            if self.flag == 0:#如果没有输入就等待输入,否则等待网络返回
                self.input_command()
            rlist = [self.client_socket]  # 接收列表
            read_list, write_list, error_list = select.select(rlist, [], [], 2)
            for sock in read_list:
                # incoming message from remote server
                if sock == self.client_socket:
                    data = sock.recv(4096)
                    if not data:
                        print '\nDisconnected from chat server'
                        sys.exit()
                    else:
                        # print data
                        self.process_data_return(data)
                        self.prompt()

其实我也不太懂为什么,把输入放到select后边就可以了

    def input_command(self):
        msg = raw_input('\nPlease input the command:')
        remote_id = raw_input("Please input remote id:")
        msg_send = "%s||%s" % (remote_id, msg)
        self.client_socket.send(msg_send)
        self.flag = 1

    def socket_handler(self):
        f = open('input.txt','w+')
        while 1:
            start = datetime.datetime.now()  # 开始时间
            rlist = [self.client_socket]  # 接收列表
            read_list, write_list, error_list = select.select(rlist, [], [], 2)
            if self.flag == 0:  # 如果没有输入就等待输入,否则等待网络返回
                self.input_command()
            for sock in read_list:
                time.sleep(0.2)
                now = datetime.datetime.now()
                if (now - start).seconds > TIMEOUT:
                    break#watchddog
                # incoming message from remote server
                if sock == self.client_socket:
                    data = sock.recv(4096)
                    if not data:
                        print '\nDisconnected from chat server'
                        sys.exit()
                    else:
                        # print data
                        self.process_data_return(data)
                        self.prompt()

 

posted @ 2017-07-25 11:30  巫谢  阅读(955)  评论(0编辑  收藏  举报