当前位置: 首页>>代码示例>>Python>>正文


Python ThreadingTCPServer.serve_forever方法代码示例

本文整理汇总了Python中socketserver.ThreadingTCPServer.serve_forever方法的典型用法代码示例。如果您正苦于以下问题:Python ThreadingTCPServer.serve_forever方法的具体用法?Python ThreadingTCPServer.serve_forever怎么用?Python ThreadingTCPServer.serve_forever使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在socketserver.ThreadingTCPServer的用法示例。


在下文中一共展示了ThreadingTCPServer.serve_forever方法的11个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。

示例1: serve_forever

# 需要导入模块: from socketserver import ThreadingTCPServer [as 别名]
# 或者: from socketserver.ThreadingTCPServer import serve_forever [as 别名]
    def serve_forever(self):
        try:

            ThreadingTCPServer.serve_forever(self)

        except Exception as e:
            if not self.run:
                return

            raise
开发者ID:bat-serjo,项目名称:vivisect,代码行数:12,代码来源:__init__.py

示例2: LogRequestHandler

# 需要导入模块: from socketserver import ThreadingTCPServer [as 别名]
# 或者: from socketserver.ThreadingTCPServer import serve_forever [as 别名]
# coding:utf-8
from socketserver import ThreadingTCPServer,StreamRequestHandler


class LogRequestHandler(StreamRequestHandler):
    def handle(self):
        print('client {} is online!'.format(self.client_address))
        filename = self.rfile.readline().decode().strip()
        fd = open('/logs/{0}'.format(filename),'a')
        while True:
            data = self.rfile.readline()
            if not data.strip():
                break
            fd.write(data.decode())
            fd.flush()
        print('close connection')
        fd.close()


if __name__ == '__main__':
    addr = ('192.168.2.53',8080)
    server = ThreadingTCPServer(addr,LogRequestHandler)
    try:
        server.serve_forever()
    except KeyboardInterrupt:
        server.shutdown()
开发者ID:ChinaChou,项目名称:py2016,代码行数:28,代码来源:logServer.py

示例3: _main

# 需要导入模块: from socketserver import ThreadingTCPServer [as 别名]
# 或者: from socketserver.ThreadingTCPServer import serve_forever [as 别名]
def _main():
    host, port = socket.gethostname(), 1536
    server = ThreadingTCPServer((host, port), TCPHandler)
    server.serve_forever()
开发者ID:crvv,项目名称:weather,代码行数:6,代码来源:tcpserver.py

示例4: WebLogHandler

# 需要导入模块: from socketserver import ThreadingTCPServer [as 别名]
# 或者: from socketserver.ThreadingTCPServer import serve_forever [as 别名]
'''
Created on 2011-9-13

@author: slieer
'''
from socketserver import BaseRequestHandler, ThreadingTCPServer
from time import sleep
import sys, socket

class WebLogHandler(BaseRequestHandler):
    def handle(self):
        print("Connected from", self.client_address)
        self.request.sendall('<hits>')
        try:
            while True:
                for hit in LOG.readlines():
                    self.request.sendall(hit)
                sleep(5)
        except socket.error:
            self.request.close()
        print("Disconnected from", self.client_address)
if __name__=='__main__':
    global LOG
    LOG = open('access-log')
    LOG.seek(0, 2)     # Start at end of current access log
    srv = ThreadingTCPServer(('',8888), WebLogHandler)
    srv.serve_forever()
开发者ID:slieer,项目名称:py,代码行数:29,代码来源:socket_server_weblog.py

示例5: params_to_d

# 需要导入模块: from socketserver import ThreadingTCPServer [as 别名]
# 或者: from socketserver.ThreadingTCPServer import serve_forever [as 别名]
        if parsedurl.path == '/code':
            self.json_headers()

            liw.authentication.authorization_code = params_to_d(self.path).get('code')
            self.wfile.write(dumps({'access_token': liw.authentication.get_access_token(),
                                    'routes': list(filter(lambda d: not d.startswith('_'), dir(liw.application)))}).encode('utf8'))
        elif parsedurl.path == '/routes':
            self.json_headers()

            self.wfile.write(dumps({'routes': list(filter(lambda d: not d.startswith('_'), dir(liw.application)))}).encode('utf8'))
        elif not authed:
            self.json_headers()

            if not globals()['run_already']:
                open_new_tab(liw.authentication.authorization_url)
            globals()['run_already'] = True
            self.wfile.write(dumps({'path': self.path, 'authed': type(liw.authentication.token) is None}).encode('utf8'))
        elif authed and len(parsedurl.path) and parsedurl.path[1:] in dir(liw.application):
            self.json_headers()
            self.wfile.write(dumps(getattr(liw.application, parsedurl.path[1:])()).encode('utf8'))
        else:
            self.json_headers(501)
            self.wfile.write(dumps({'error': 'NotImplemented'}).encode('utf8'))


if __name__ == '__main__':
    httpd = ThreadingTCPServer(('localhost', PORT), CustomHandler)

    print('Server started on port:{}'.format(PORT))
    httpd.serve_forever()
开发者ID:Dankeee,项目名称:spider,代码行数:32,代码来源:http_api.py

示例6: ModbusServer

# 需要导入模块: from socketserver import ThreadingTCPServer [as 别名]
# 或者: from socketserver.ThreadingTCPServer import serve_forever [as 别名]

#.........这里部分代码省略.........
                elif rx_bd_fc is const.WRITE_SINGLE_REGISTER:
                    (w_address, w_value) = struct.unpack('>HH', rx_body[1:])
                    if DataBank.set_words(w_address, [w_value]):
                        # send write ok frame
                        tx_body = struct.pack('>BHH', rx_bd_fc, w_address, w_value)
                    else:
                        exp_status = const.EXP_DATA_ADDRESS
                # function Write Multiple Coils (0x0F)
                elif rx_bd_fc is const.WRITE_MULTIPLE_COILS:
                    (b_address, b_count, byte_count) = struct.unpack('>HHB', rx_body[1:6])
                    # check quantity of updated coils
                    if (0x0001 <= b_count <= 0x07B0) and (byte_count >= (b_count/8)):
                        # allocate bits list
                        bits_l = [False] * b_count
                        # populate bits list with bits from rx frame
                        for i, item in enumerate(bits_l):
                            b_bit_pos = int(i/8)+6
                            b_bit_val = struct.unpack('B', rx_body[b_bit_pos:b_bit_pos+1])[0]
                            bits_l[i] = test_bit(b_bit_val, i % 8)
                        # write words to data bank
                        if DataBank.set_bits(b_address, bits_l):
                            # send write ok frame
                            tx_body = struct.pack('>BHH', rx_bd_fc, b_address, b_count)
                        else:
                            exp_status = const.EXP_DATA_ADDRESS
                    else:
                        exp_status = const.EXP_DATA_VALUE
                # function Write Multiple Registers (0x10)
                elif rx_bd_fc is const.WRITE_MULTIPLE_REGISTERS:
                    (w_address, w_count, byte_count) = struct.unpack('>HHB', rx_body[1:6])
                    # check quantity of updated words
                    if (0x0001 <= w_count <= 0x007B) and (byte_count == w_count * 2):
                        # allocate words list
                        words_l = [0] * w_count
                        # populate words list with words from rx frame
                        for i, item in enumerate(words_l):
                            w_offset = i * 2 + 6
                            words_l[i] = struct.unpack('>H', rx_body[w_offset:w_offset + 2])[0]
                        # write words to data bank
                        if DataBank.set_words(w_address, words_l):
                            # send write ok frame
                            tx_body = struct.pack('>BHH', rx_bd_fc, w_address, w_count)
                        else:
                            exp_status = const.EXP_DATA_ADDRESS
                    else:
                        exp_status = const.EXP_DATA_VALUE
                else:
                    exp_status = const.EXP_ILLEGAL_FUNCTION
                # check exception
                if exp_status != const.EXP_NONE:
                    # format body of frame with exception status
                    tx_body = struct.pack('BB', rx_bd_fc + 0x80, exp_status)
                # build frame header
                tx_head = struct.pack('>HHHB', rx_hd_tr_id, rx_hd_pr_id, len(tx_body) + 1, rx_hd_unit_id)
                # send frame
                self.request.send(tx_head + tx_body)
            self.request.close()

    def __init__(self, host='localhost', port=502, no_block=False, ipv6=False):
        """Constructor

        Modbus server constructor.

        :param host: hostname or IPv4/IPv6 address server address (optional)
        :type host: str
        :param port: TCP port number (optional)
        :type port: int
        :param no_block: set no block mode, in this mode start() return (optional)
        :type no_block: bool
        :param ipv6: use ipv6 stack
        :type ipv6: bool
        """
        self.host = host
        self.port = port
        self.no_block = no_block
        self.ipv6 = ipv6
        # set class attribute
        ThreadingTCPServer.address_family = socket.AF_INET6 if self.ipv6 else socket.AF_INET
        ThreadingTCPServer.daemon_threads = True
        # init server
        self._service = ThreadingTCPServer((self.host, self.port), self.ModbusService, bind_and_activate=False)
        # set socket options
        self._service.socket.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
        self._service.socket.setsockopt(socket.SOL_SOCKET, socket.SO_KEEPALIVE, 1)
        # TODO test no_delay with bench
        self._service.socket.setsockopt(socket.IPPROTO_TCP, socket.TCP_NODELAY, 1)
        # add thread for no block mode
        if self.no_block:
            self._serve_th = Thread(target=self._service.serve_forever)
            self._serve_th.daemon = True

    def start(self):
        # bind and activate
        self._service.server_bind()
        self._service.server_activate()
        # serve request
        if self.no_block:
            self._serve_th.start()
        else:
            self._service.serve_forever()
开发者ID:Siuol,项目名称:pyModbusTCP,代码行数:104,代码来源:server.py

示例7: encrypt_message

# 需要导入模块: from socketserver import ThreadingTCPServer [as 别名]
# 或者: from socketserver.ThreadingTCPServer import serve_forever [as 别名]
	encrypted_message = encrypt_message(pw.encode('utf-8'), b'Hello world!!!!!')
	print(encrypted_message)
	o_message = decrypt_message(pw.encode('utf-8'), encrypted_message)
	print(o_message)
	# 发起一个线程, 扫描信息
	thread = Thread(target = scan_messages, args = (10, ))
	thread.start()
	print ("thread finished...exiting")


	station_name = 'sv_station';
	with open('public.pem','r') as f:
		station_pubic_key = f.read();
	with open('private.pem','r') as f:
		station_private_key = f.read();
	
	station_fingerprint = rsa_sign(station_name.encode('utf-8'), station_private_key, '111111');
	station_address = btc_build_address( station_fingerprint );
	# text = decrypt(station_private_key, encrypted_key);
	# print(text);
	with open('resources/moki_public_key.pem','r') as f:
		moki_pub = f.read();
	HOST = '0.0.0.0'
	PORT = 8998;
	ADDR = (HOST,PORT);
	socketserver.TCPServer.allow_reuse_address = True;
	server = ThreadingTCPServer(ADDR,Handler)  #参数为监听地址和已建立连接的处理类
	print( station_name+'@'+ station_address +' is listening...');
	server.serve_forever()  #监听,建立好TCP连接后,为该连接创建新的socket和线程,并由处理类中的handle方法处理
	print(server);
开发者ID:selvn,项目名称:dimp,代码行数:32,代码来源:server_start.py

示例8: handle

# 需要导入模块: from socketserver import ThreadingTCPServer [as 别名]
# 或者: from socketserver.ThreadingTCPServer import serve_forever [as 别名]
        finally:
            return result

    def handle(self):
        if self.checkconf():
            data = self.readconf()
            self.writeconf(data)
        else:
            confsfile = open(self.confsfile)
            self.confs = loads(confsfile.read())
            confsfile.close()
        for i in self.confs:
            print(str(i)+'=>'+self.confs[str(i)]['name']+'=>'+self.confs[str(i)]['cont'])
            data = urlopen(self.confs[str(i)]['cont']).read().decode('utf-8')
            print(data)
        print(self.client_address)
        if self.client_address[0] in self.safeip:
            print('此IP允许访问')
            sleep(60)
            self.data = self.request.recv(10240)
            self.request.sendall('收到的请求内容是'.encode('utf-8') + self.data)
        else:
            print('此IP不允许访问')
# 变动位置
if __name__=="__main__":
    TCP.allow_reuse_address=True
    tcpServ = TTCP(ADDR, MyRequestHandler)
    print('等待新的连接。。。。')
    tcpServ.serve_forever()

开发者ID:chenpenghuan,项目名称:Test,代码行数:31,代码来源:tcpserver.py

示例9: print

# 需要导入模块: from socketserver import ThreadingTCPServer [as 别名]
# 或者: from socketserver.ThreadingTCPServer import serve_forever [as 别名]
conn, addr = svrSock.accept()

recvBuf = conn.recv(1024)
print(len(recvBuf))
print(recvBuf)
'''


'''
    우선 연결된 클라이언트 정보를 저장해서 allSend(가칭)를 구현해서 클라이언트도 대화내용을 알게해야한다!
    대화 내용을 allSend로 보낼 때 들어온 메세지가 시간 순서에 맞게 되는지 항상 확인한다(?) --> 이게 오늘의 과제였나?
'''
from socketserver import ThreadingTCPServer, StreamRequestHandler

PORT = 2000

class MyRequestHandler(StreamRequestHandler):
    def handle(self):
        conn = self.request
        print('connection form', self.client_address)
        buf = conn.recv(1024)
        if not buf:
            print('nothing')
        else:
            print(buf.decode('utf-8'))


server = ThreadingTCPServer(('127.0.0.1', 2000), MyRequestHandler)
print('listening on port', PORT)
server.serve_forever()          # 얘는 한번만 실행되고 끝난다. 이걸 반복시킬 방법을 찾아야 한다!
开发者ID:skykhk01,项目名称:python,代码行数:32,代码来源:server.py

示例10: _broadcast

# 需要导入模块: from socketserver import ThreadingTCPServer [as 别名]
# 或者: from socketserver.ThreadingTCPServer import serve_forever [as 别名]
    active = True
    while active:
      transmission = self.request.recv(1024).decode()           # wait for something to happen
      if transmission:
        command = transmission.split()[0]
        data = transmission[1+len(command): ]          # the rest

        if command == 'ADD':
          username = data.strip()
          _socketLookup[username] = self.request
          _broadcast(('NEW %s\n' % username).encode())
        elif command == 'MESSAGE':
          _broadcast(('MESSAGE %s\n%s\n' % (username,data)).encode() )
        elif command == 'PRIVATE':
          rcpt = data.split('\n')[0]
          if rcpt in _socketLookup:
            content = data.split('\n')[1]
            _socketLookup[rcpt].send(('PRIVATE %s\n%s\n'%(username,content)).encode() )
        elif command == 'QUIT':
          active = False
          self.request.send('GOODBYE\n'.encode())                  # acknowledge
      else:
          active = False                                  # socket failed
    
    self.request.close()
    _socketLookup.pop(username)
    _broadcast(('LEFT %s\n' % username).encode())                    # inform others

myServer = ThreadingTCPServer( ('localhost', 9000), ChatHandler)
myServer.serve_forever()
开发者ID:OthmanEmpire,项目名称:university_code,代码行数:32,代码来源:chatserver.py

示例11: main

# 需要导入模块: from socketserver import ThreadingTCPServer [as 别名]
# 或者: from socketserver.ThreadingTCPServer import serve_forever [as 别名]
def main():
    """
    Create and start server.
    """
    server = ThreadingTCPServer(('', 7000), ProbeHandler)
    server.serve_forever()
开发者ID:bmaca,项目名称:proby,代码行数:8,代码来源:proby.py


注:本文中的socketserver.ThreadingTCPServer.serve_forever方法示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。