def run_server(port, site_dir, ctx): output_dir = ctx["OutputDir"] # start server class RequestHandler(SimpleHTTPRequestHandler): def do_GET(self): if hasattr(self, "error") and self.error is not None: self.send_response(200, 'OK') self.send_header('Content-type', 'html') self.end_headers() self.wfile.write(bytes(self.error, 'UTF-8')) else: super().do_GET() def translate_path(self, path): return os.path.join(site_dir, output_dir, path[1:]) handler = RequestHandler httpd = TCPServer(("", port), handler) atexit_register(lambda: httpd.shutdown()) # start update thread thread = Thread(target=update, args=(site_dir, ctx, handler, port)) thread.daemon = True thread.start() print("Serving at http://localhost:" + str(port) + "/") httpd.serve_forever()
class PickleServer: def __init__(self, address): ''' @param address: A tuple of ip and port. For example, PickleServer(('127.0.0.1', 3750)) ''' handler = self.handle from socketserver import StreamRequestHandler class Handler(StreamRequestHandler): def handle(self): from pclib import iostream stream = iostream(self.rfile, self.wfile) stream = PickleStream(stream) handler(stream) from socketserver import TCPServer self.server = TCPServer(address, Handler) def start(self): from threading import Thread Thread(target = self.run).start() def run(self): self.server.serve_forever() def shutdown(self): self.server.shutdown() def handle(self, stream): pass
def main(): host = '' port = 7777 server = None board = PyMata3(5) shoulder = Actuator(board, 9) arm = Actuator(board, 10) elbow = Actuator(board, 11, min_angle=-90, max_angle=90, offset=-90) global mech_arm mech_arm = MechanicalArm( [shoulder, arm, elbow], Fabrik( joint_positions=[Vector2(0, 0), Vector2(53, 0), Vector2(100, 0)], link_lengths=[53, 47], tolerance=0.1 ) ) sleep(2) while server is None: try: server = TCPServer((host, port), ConnectionHandler) except OSError: port += 1 continue print("Serving on: {}".format(port)) server.serve_forever() server.server_close()
class server(object): def __init__(self, offtime): self.offtime = offtime self.server = TCPServer( ('127.0.0.1', 7654), BaseRequestHandler ) self.server_thread = None self.server.running = False def shutdown(self, signum, frame): print("[*] Shutting down server thread") self.server.running = False self.server.shutdown() def up(self): signal.signal(signal.SIGTERM, self.shutdown) signal.signal(signal.SIGINT, self.shutdown) signal.signal(signal.SIGALRM, self.shutdown) signal.alarm(self.offtime) self.server_thread = threading.Thread(target=self.server.serve_forever) print("[*] Starting server thread") self.server_thread.start() self.server.running = True print("[*] Waiting for server thread to shut down") while self.server.running: time.sleep(1) self.server_thread.join() print("[*] Server thread terminated")
def main(): sys.excepthook = Pyro4.util.excepthook print("Welcome to the prototype !\n") print("Would you like to be [s]erver or [c]lient? (s/c)") user_interaction = input(":> ").strip() if "s" == user_interaction: print("Please enter the IP-Address which the server should listen on.") ip_adr = input(":> ").strip() rl_ip_adr = Pyro4.socketutil.getInterfaceAddress(ip_adr) print("\nIMPORTANT: The Server will listen on: %s" % rl_ip_adr) HOST, PORT = rl_ip_adr, 20111 daemon = Pyro4.Daemon(host=rl_ip_adr) srv_uri = daemon.register(Server()) tcpserver = TCPServer((HOST, PORT), lambda *args, **keys: SingleTCPHandler(send_server_uri, srv_uri.asString(), *args, **keys)) t = threading.Thread(target=tcpserver.serve_forever) t.start() print("Serving...") daemon.requestLoop() tcpserver.shutdown() elif "c" == user_interaction: print("Please enter your name.") name = input(":> ").strip() print("Please enter the ip of the server.") srv_ip = input(":> ").strip() client = Client(name, srv_ip) clt_uri = client.get_uri().asString() TCPSender.send(clt_uri, (srv_ip, 20111)) client.start() while client.is_running(): time.sleep(1) contact = Contact(name, client.get_srv_uri()) contact.register() input("Press Enter to exit.") contact.deregister()
def start(self): TCPServer.__init__(self, ('localhost', int(HTTP_PORT)), CustomHandler) self.RESOURCE_LOCATION = path.abspath(path.dirname(__file__)) print("Server serving from DocumentRoot:" + self.RESOURCE_LOCATION) chdir(self.RESOURCE_LOCATION) server_thread = threading.Thread(name='test_file_server', target=self.serve_forever) server_thread.daemon = True server_thread.start()
def runserver(config=None): if config is None: config={'host':'','port':200} serv=TCPServer((config['host'],config['port']),MyHandler) print('listening port: '+str(config['port'])) print('server name : svncount') print('server type : tcp') serv.serve_forever()
class MobileServer: def __init__(self, address): ''' @param address: A tuple of ip and port. ''' from socketserver import TCPServer self.server = TCPServer(address, MobileHandler) def run(self): self.server.serve_forever()
def iiif_server(): address = ('localhost', 0) httpd = TCPServer(address, SimpleHTTPRequestHandler) t = threading.Thread(target=httpd.serve_forever) t.start() yield httpd.server_address httpd.shutdown() t.join()
def run(self): """ Main thread method. Open socket and waiting for connections. """ server = TCPServer((self.host, self.port), TCPHandler) server.lymphocytes_getter = self.lymphocytes_getter # runs forever - so make this thread daemon server.serve_forever()
def start_server_for_ips(): serv = TCPServer(('', 20007), EchoHandler) ser = Thread(target=serv.serve_forever) ser.start() global members_count members_count = 2 while members_count: sleep(1) serv.shutdown()
def serve_forever(self, poll_interval=0.5): """Handle one request at a time until shutdown. Polls for shutdown every poll_interval seconds. Ignores self.timeout. If you need to do periodic tasks, do them in another thread. """ self._serving_event.set() self._shutdown_request_event.clear() TCPServer.serve_forever(self, poll_interval=poll_interval)
def server_close(self): """ Closes the socket server and any associated resources. """ self.log.debug("Closing the socket server connection.") TCPServer.server_close(self) self.queue_manager.close() self.topic_manager.close() if hasattr(self.authenticator, 'close'): self.authenticator.close() self.shutdown()
def serve(self): self.monitor() os.chdir(self.directory) request_handler = server.SimpleHTTPRequestHandler httpd = TCPServer(('', self.port), request_handler) try: print('Preview available at http://0.0.0.0:{}/'.format(self.port)) httpd.serve_forever() except KeyboardInterrupt: httpd.shutdown()
class SimpleServer(Thread): def __init__(self): Thread.__init__(self) self.httpd = None def run(self): chdir(root + "/_site") self.httpd = TCPServer(('', 8000), SimpleHTTPRequestHandler) self.httpd.serve_forever() def shutdown(self): self.httpd.shutdown()
def __init__(self, server_address, # Server address (host,port) RequestHandlerClass, certfile, # Certificate path keyfile, # Key path ssl_version=ssl.PROTOCOL_SSLv23, #Comunicatio+n protocol ciphers="DEFAULT", bind_and_activate=True): TCPServer.__init__(self, server_address, RequestHandlerClass, bind_and_activate) self.certfile = certfile self.keyfile = keyfile self.ssl_version = ssl_version self.ciphers=ciphers
def __init__(self, server_address, RequestHandlerClass, certfile, keyfile, bind_and_activate=True): TCPServer.__init__(self, server_address, RequestHandlerClass) self.socket = ssl.wrap_socket(socket.socket(self.address_family, self.socket_type), server_side=True, certfile=certfile, keyfile=keyfile, do_handshake_on_connect=False) if bind_and_activate: self.server_bind() self.server_activate()
def server_bind(self): """ Override server_bind to store the server name, even in IronPython. See https://ironpython.codeplex.com/workitem/29477 """ TCPServer.server_bind(self) host, port = self.socket.getsockname()[:2] self.server_port = port try: self.server_name = socket.getfqdn(host) except ValueError: # Use the local host name in case of error, like CPython does self.server_name = socket.gethostname()
def serve(self): cwd = os.getcwd() os.chdir(self.directory) httpd = TCPServer(("", self.port), SimpleHTTPRequestHandler) try: self.logger.log( "server running on http://localhost:{0}".format(self.port) ) httpd.serve_forever() except KeyboardInterrupt: self.logger.log("shutting down server\n") os.chdir(cwd)
def main(): global KADECOT_IP_ADDRESS PORT = 31338 if len(sys.argv) > 1: KADECOT_IP_ADDRESS = sys.argv[1] else: KADECOT_IP_ADDRESS = input("Kadeoct JSONServer IP: ") Handler = SnapKadecotHTTPRequestHandler print("KadecotServer: " + KADECOT_IP_ADDRESS + ":" + str(PORT)) httpd = TCPServer(("", PORT), Handler) print("serving at port", PORT) print("http://snap.berkeley.edu/snapsource/snap.html#open:http://localhost:"+str(PORT)+"/block") httpd.serve_forever()
def main(): ap = argparse.ArgumentParser() ap.add_argument('port', nargs='?', type=int, default='8000') args = ap.parse_args() port = args.port try: httpd = TCPServer(("", port), Handler) url = 'http://127.0.0.1:{}/crowdmap'.format(port) print ("Open this url in your browser: {}".format(url)) webbrowser.open_new(url) httpd.serve_forever() except KeyboardInterrupt: print ('port {} closed'.format(port))
def cmd_serve(self, *args): '''Serve the bin directory via SimpleHTTPServer ''' try: from http.server import SimpleHTTPRequestHandler from socketserver import TCPServer except ImportError: from SimpleHTTPServer import SimpleHTTPRequestHandler from SocketServer import TCPServer os.chdir(self.bin_dir) handler = SimpleHTTPRequestHandler httpd = TCPServer(("", SIMPLE_HTTP_SERVER_PORT), handler) print("Serving via HTTP at port {}".format(SIMPLE_HTTP_SERVER_PORT)) print("Press Ctrl+c to quit serving.") httpd.serve_forever()
def __init__(self, address, handler): class a(StreamRequestHandler): def handle(self): stream = iostream(self.rfile, self.wfile) stream = objectstream(stream) handler(stream) self._server = TCPServer(address, a)
class netserver: def __init__(self, address, handler): class a(StreamRequestHandler): def handle(self): stream = iostream(self.rfile, self.wfile) stream = objectstream(stream) handler(stream) self._server = TCPServer(address, a) def start(self): Thread(target = self.run).start() def run(self): self._server.serve_forever() def shutdown(self): self._server.shutdown()
def __init__(self, request_count=100, port=9999, path='.', queue=None): self.request_count = request_count self.queue = queue self.port = port self.httpd = TCPServer(("", self.port), Handler) self.path = os.path.abspath(path) + '/marathon_log.json' self.counter = 0 print('Server listening on port {}'.format(port))
def main(*args): """ Function invoked when the server is run as a script""" import argparse desc = "nframe server" parser = argparse.ArgumentParser(description=desc) parser.add_argument("-i", "--ip", default="0.0.0.0", help="IP address of server") parser.add_argument("-p", "--port", default=7645, help="Port of server") parser.add_argument("--import", action="store", default=False, dest="import_file", help="Import data before starting server") parser.add_argument("--export", action="store", default=False, dest="export_file", help="Export data then exits") parser.add_argument("--force-unlock", action="store_true", default=False, help="Remove lock file without discretion", dest="force_unlock") parser.add_argument("--exit", action="store_true", default=False, help="perform action then exit (don't run server)", dest="exit") pargs = parser.parse_args(args) if args else parser.parse_args() if pargs.force_unlock: Lock().force_release() if pargs.import_file: with Data(timeout=5) as import_data: import_data.import_data(pargs.import_file) if pargs.export_file: with Data(timeout=5) as export_data: export_data.export_data(pargs.export_file) return server = TCPServer((pargs.ip, pargs.port), Server) if pargs.exit: return pargs with Lock(timeout=5): try: server.serve_forever() except (SystemError, SystemExit, KeyboardInterrupt): server.server_close()
def __init__(self, offtime): self.offtime = offtime self.server = TCPServer( ('127.0.0.1', 7654), BaseRequestHandler ) self.server_thread = None self.server.running = False
def setUpClass(self): self.mute_server = TCPServer(('localhost', 0), GitTimeoutTest.MuteHandler) _, self.mute_port = self.mute_server.server_address serv_thread = threading.Thread(target=self.mute_server.serve_forever) serv_thread.daemon = True serv_thread.start() self.root_directory = tempfile.mkdtemp() self.local_path = os.path.join(self.root_directory, "ros")
class HttpServer(Thread): """A simple HTTP Server in its own thread""" def __init__(self, port): super(HttpServer, self).__init__() self.daemon = True handler = SimpleHTTPRequestHandler self.httpd = TCPServer(("", port), handler) def run(self): """Start the server""" print('Start HTTP server') self.httpd.serve_forever() def stop(self): """Stop the server""" print('Stop HTTP server') self.httpd.socket.close()
class GitTimeoutTest(unittest.TestCase): class MuteHandler(BaseRequestHandler): def handle(self): data = True while data: data = self.request.recv(1024) @classmethod def setUpClass(self): self.mute_server = TCPServer(('localhost', 0), GitTimeoutTest.MuteHandler) _, self.mute_port = self.mute_server.server_address serv_thread = threading.Thread(target=self.mute_server.serve_forever) serv_thread.daemon = True serv_thread.start() self.root_directory = tempfile.mkdtemp() self.local_path = os.path.join(self.root_directory, "ros") def test_checkout_timeout(self): ## SSH'ing to a mute server will hang for a very long time url = 'ssh://[email protected]:{0}/test'.format(self.mute_port) client = GitClient(self.local_path) start = time.time() self.assertFalse(client.checkout(url, timeout=2.0)) stop = time.time() self.assertTrue(stop - start > 1.9) self.assertTrue(stop - start < 3.0) # the git processes will clean up the checkout dir, we have to wait # for them to finish in order to avoid a race condition with rmtree() while os.path.exists(self.local_path): time.sleep(0.2) @classmethod def tearDownClass(self): self.mute_server.shutdown() if os.path.exists(self.root_directory): shutil.rmtree(self.root_directory) def tearDown(self): if os.path.exists(self.local_path): shutil.rmtree(self.local_path)
help= 'Use the combined weights for all tracks, rather than selecting the weights file based off of the course code sent by the Play.lua script.', default=False) parser.add_argument('-p', '--port', type=int, help='Port number', default=36296) parser.add_argument('-c', '--cpu', action='store_true', help='Force Tensorflow to use the CPU.', default=False) args = parser.parse_args() if args.cpu: os.environ["CUDA_DEVICE_ORDER"] = "PCI_BUS_ID" os.environ["CUDA_VISIBLE_DEVICES"] = "-1" logger.info("Loading model...") model = create_model(keep_prob=1) model2 = joblib.load('use_item_v3.m') model_yolo = create_yolo() if args.all: model.load_weights('weights/all.hdf5') logger.info("Starting server...") server = TCPServer(('0.0.0.0', args.port), TCPHandler) print("Listening on Port: {}".format(server.server_address[1])) sys.stdout.flush() server.serve_forever()
def __init__(self, *args, **kwargs): TCPServer.__init__(self, *args, **kwargs) self._server_replies = bytearray(b'') self._client_sends = []
from http.server import SimpleHTTPRequestHandler from socketserver import TCPServer import logging PORT = 1234 class GetHandler(SimpleHTTPRequestHandler): def do_GET(self): logging.error(self.headers) SimpleHTTPRequestHandler.do_GET(self) Handler = GetHandler httpd = TCPServer(("", PORT), Handler) httpd.serve_forever()
from socketserver import TCPServer from step_c_networking.handler import TCPEchoHandler print('waiting ...') server = TCPServer(('localhost', 20000), TCPEchoHandler) server.serve_forever()
from socketserver import TCPServer, StreamRequestHandler ADDRESS = "", 8085 class EchoHandler(StreamRequestHandler): """Responde requisições repetindo o que foi recebido.""" def handle(self): # Usar b'' é um jeito literal de escrever bytes em ascii self.wfile.write(b"Hello, World!\n") # self.wfile e self.rfile são canais de entrada e saída # programados para ter a mesma interface de arquivos! for line in self.rfile: # esta linha responde o cliente self.wfile.write(line) # esta linha imprime no console print(line.decode('ascii').strip()) if __name__ == "__main__": # usando with nosso TCPServer vai arrumar a casa direitinho quando encerrado with TCPServer(ADDRESS, EchoHandler) as server: server.serve_forever()
def __init__(self, do_ssl=False, paypal_mode='valid'): TCPServer.__init__(self, ("", 0), Handler) # old-style base? self.do_ssl = do_ssl self.paypal_mode = paypal_mode self.last_request_body = None self.last_request_content_type = None
def shutdown(self): return TCPServer.shutdown(self)
elif msg_dict["type"] == "save_ts_to_db": times = np.array(msg_dict["ts"])[:, 0] values = np.array(msg_dict["ts"])[:, 1] try: full_ts = ats.ArrayTimeSeries(times=times, values=values) tsid = add_ts(full_ts) payload = {'tsid': tsid} except ValueError as ve: payload = {'error_type': 'ValueError', 'error': str(ve)} # Unrecognized message type else: payload = { 'error_type': 'ValueError', 'error': ("Message type '%s' is unrecognized" % msg_dict["type"]) } # Step 3. dictionary to json payload = json.dumps(payload) # Setp 4. json to byte and send back to client self.request.send(serialize(payload)) if __name__ == '__main__': rebuild_if_needed(LIGHT_CURVES_DIR, DB_DIR) serv = TCPServer(('', PORT), SocketServer) serv.serve_forever()
#!/usr/bin/env python3 from http.server import SimpleHTTPRequestHandler from socketserver import TCPServer PORT = 8000 class CORSRequestHandler(SimpleHTTPRequestHandler): def end_headers(self): self.send_header("Access-Control-Allow-Origin", "*") super().end_headers() with TCPServer(("", PORT), CORSRequestHandler) as httpd: print("Serving at port", PORT) httpd.serve_forever()
class PannellumTester(object): """Bring up a server with a testing robot. """ def __init__(self, port=None, browser="Chrome", headless=False): self.handler = PannellumServer if port: self.port = port else: self.port = choice(range(8000, 9999)) print("Selected port is %s" % self.port) self.httpd = TCPServer(("", self.port), self.handler) self.server = Thread(target=self.httpd.serve_forever) self.server.setDaemon(True) self.server.start() self.started = True self.pause_time = 100 self.browser = None self.headless = headless self.display = None self.driver = browser def take_screenshot(self, element_id, filename=None): """Take a screenshot of an element with a given ID. """ element = self.browser.find_element(By.ID, element_id) img = Image.open(io.BytesIO(element.screenshot_as_png)).convert("RGB") if filename is not None: img.save(filename) return img def equal_images(self, reference, comparator, name, threshold=5): """Compare two images, both loaded with PIL, based on pixel differences.""" diff = np.mean(np.array(ImageChops.difference(reference, comparator))) print("%s difference: %s" % (name, diff)) if diff >= threshold: comparator.save("tests/" + name + "-comparison.png") raise ValueError("Screenshot difference is above threshold!") def run_tests(self, create_ref=False): """Run tests for Pannellum.""" print("Loading page...") self.get_page("http://localhost:%s/tests/tests.html" % self.port) print("Running tests...") time.sleep(5) assert self.browser.execute_script("return viewer.isLoaded()") is True # Check equirectangular assert self.browser.execute_script( "return viewer.getScene() == 'equirectangular'") if create_ref: self.take_screenshot("panorama", "tests/equirectangular.png") subprocess.call([ "optipng", "-o7", "-strip", "all", "tests/equirectangular.png" ]) else: reference = Image.open("tests/equirectangular.png") comparator = self.take_screenshot("panorama") self.equal_images(reference, comparator, "equirectangular") print("PASS: equirectangular") # Check movement self.browser.execute_script( "viewer.setPitch(30).setYaw(-20).setHfov(90)") time.sleep(2) assert self.browser.execute_script( "return viewer.getPitch() == 30 && viewer.getYaw() == -20 && viewer.getHfov() == 90" ) self.browser.find_element(By.CLASS_NAME, "pnlm-zoom-in").click() time.sleep(1) assert self.browser.execute_script("return viewer.getHfov() == 85") self.browser.find_element(By.CLASS_NAME, "pnlm-zoom-out").click() time.sleep(1) assert self.browser.execute_script("return viewer.getHfov() == 90") print("PASS: movement") # Check look at self.browser.execute_script("viewer.lookAt(-10, 90, 100)") time.sleep(2) assert self.browser.execute_script( "return viewer.getPitch() == -10 && viewer.getYaw() == 90 && viewer.getHfov() == 100" ) print("PASS: look at") # Check cube self.browser.execute_script("viewer.loadScene('cube')") time.sleep(5) assert self.browser.execute_script( "return viewer.getScene() == 'cube'") if create_ref: self.take_screenshot("panorama", "tests/cube.png") subprocess.call( ["optipng", "-o7", "-strip", "all", "tests/cube.png"]) else: reference = Image.open("tests/cube.png") comparator = self.take_screenshot("panorama") self.equal_images(reference, comparator, "cube") # Check to make sure hotspots are below controls self.browser.execute_script("viewer.setPitch(-35)") self.browser.execute_script("viewer.setYaw(32)") time.sleep(2) action = ActionChains(self.browser) elem = self.browser.find_element(By.CLASS_NAME, "pnlm-zoom-in") action.move_to_element(elem).move_by_offset(1, 1).click().perform() assert self.browser.execute_script("return viewer.getHfov() == 95") print("PASS: hot spots below UI") # Check hot spot self.browser.find_element(By.CLASS_NAME, "pnlm-scene").click() time.sleep(5) assert self.browser.execute_script( "return viewer.getScene() == 'multires'") print("PASS: hot spot") # Check multires if create_ref: self.take_screenshot("panorama", "tests/multires.png") subprocess.call( ["optipng", "-o7", "-strip", "all", "tests/multires.png"]) else: reference = Image.open("tests/multires.png") comparator = self.take_screenshot("panorama") self.equal_images(reference, comparator, "multires") # Check hotspot dragging - move from (20, 20) to (0, 0) action = ActionChains(self.browser) action.drag_and_drop( self.browser.find_element(By.CLASS_NAME, "pnlm-hotspot"), self.browser.find_element( By.CLASS_NAME, "pnlm-render-container"), # drops in the middle of the element ) action.perform() time.sleep(1) assert self.browser.execute_script( "var hs = viewer.getConfig().hotSpots[0]; return Math.abs(hs.yaw) < 0.001 && Math.abs(hs.pitch) < 0.001" ) print("PASS: hot spot dragging") self.httpd.server_close() def get_browser(self, name=None): """Return a browser if it hasn't been initialized yet. """ if name is None: name = self.driver log_path = "tests/%s-driver.log" % name.lower() if self.browser is None: if name.lower() == "firefox": fp = webdriver.FirefoxProfile() fp.set_preference("layout.css.devPixelsPerPx", "1.0") self.browser = webdriver.Firefox(service_log_path=log_path, firefox_profile=fp) self.browser.set_window_size(800, 600) else: options = webdriver.ChromeOptions() options.add_argument("headless") options.add_argument("no-sandbox") options.add_argument("window-size=800x600") self.browser = webdriver.Chrome(service_log_path=log_path, options=options) return self.browser def get_page(self, url): """Open a particular URL, checking for timeout. """ if self.browser is None: self.browser = self.get_browser() try: return self.browser.get(url) except TimeoutException: print( "Browser request timeout. Are you connected to the internet?") self.browser.close() sys.exit(1) def stop(self): """Close any running browser or server and shut down the robot. """ if self.browser is not None: self.browser.close() self.httpd.server_close() if self.display is not None: self.display.close()
print('Got connection from', self.client_address) while True: msg = self.request.recv(8192) if not msg: break self.request.send(msg) ''' class EchoHandler(StreamRequestHandler): def handle(self): print("Got connect from ", self.client_address) for line in self.rfile: self.wfile.write(line) ''' if __name__ == "__main__": ''' #serv = TCPServer(('', 20000), EchoHandler) serv = ThreadingTCPServer(('', 20000), EchoHandler) serv.serve_forever() ''' from threading import Thread NWORKERS = 5 serv = TCPServer(('', 20000), EchoHandler) for n in range(NWORKERS): t = Thread(target=serv.serve_forever) t.daemon = True t.start() serv.serve_forever()
def __init__(self, port): TCPServer.__init__(self, ("", port), QuietHandler) self.process = multiprocessing.Process(target=self.serve_forever)
Created on Apr 1, 2015 @author: RW Taggart This is a simple example based on one from the internet. ''' from http.server import BaseHTTPRequestHandler, HTTPServer from socketserver import TCPServer class ExampleHTTPHandler(BaseHTTPRequestHandler): def do_GET(self): self.send_response(200) self.send_header('Content-type', 'text/html') self.end_headers() self.wfile.write(b'Hello World!') return if __name__ == "__main__": port = 8000 # exampleServer = HTTPServer(("", port), ExampleHTTPHandler) exampleServer = TCPServer(("", port), ExampleHTTPHandler) print("Started server on port " + str(port) + ".") try: exampleServer.serve_forever() except KeyboardInterrupt: exampleServer.socket.close()
def run(): httpd = TCPServer((config.NOTIFY_ADDR, config.NOTIFY_PORT), Handler) logger.info('Server started...') httpd.serve_forever()
#!/usr/bin/python #-*- coding:UTF-8 -*- # 网络编程(使用线程技术 Threading) #a03thrdsvr.py from socketserver import TCPServer, ThreadingMixIn, StreamRequestHandler class Server(ThreadingMixIn, TCPServer): pass class Handler(StreamRequestHandler): def handle(self): addr = self.request.getpeername() print('Got connection from:', addr) self.wfile.write( bytes('Thank you for connecting (Threading)', encoding="utf-8")) #server = TCPServer(('', 1234), Handler) server = TCPServer(("127.0.0.1", 8080), Handler) server.serve_forever()
from socketserver import (TCPServer as TCP, StreamRequestHandler as SRH) from time import ctime HOST = '' PORT = 21567 ADDR = (HOST, PORT) class MyRequestHandler(SRH): def handle(self): print('...connected from:', self.client_address) self.wfile.write( bytes('[%s] %s' % (bytes(ctime(), 'utf-8'), self.rfile.readline()), 'utf-8')) tcpServ = TCP(ADDR, MyRequestHandler) print('waiting for connection ...') tcpServ.serve_forever()
def __init__(self, server_address): """Initialization of MSLTCPServer""" common.info('Constructing NetflixTCPServer') self.netflix_session = NetflixSession() TCPServer.__init__(self, server_address, NetflixHttpRequestHandler)
def serve_forever(self): """Forward.""" self.is_serving = True TCPServer.serve_forever(self)
def run(self, address): # 创建web服务器并且运行 UserverHandler.routes = self.routes with TCPServer(address, UserverHandler) as s: s.serve_forever()
def preview_main(gen_script, default_port): """Main entrypoint for previewing documentation. Args: gen_script: Generation script, required to generate docs. default_port: Default port for local HTTP server. """ assert isfile(_SPHINX_BUILD), "Please execute via 'bazel run'" parser = argparse.ArgumentParser() parser.register('type', 'bool', _str2bool) parser.add_argument( "--browser", type='bool', default=True, metavar='BOOL', help="Open browser. Disable this if you are frequently recompiling.") parser.add_argument( "--port", type=int, default=default_port, metavar='PORT', help="Port for serving doc pages with a HTTP server.") parser.add_argument( "--generates", type='bool', default=False, metavar='BOOL', help="Only generates.") args = parser.parse_args() if args.generates: from gen_sphinx import write_doc_modules write_doc_modules(dirname(gen_script)) else: # Choose an arbitrary location for generating documentation. out_dir = abspath("_build") if isdir(out_dir): rmtree(out_dir) # Generate. check_call([sys.executable, gen_script, "--out_dir", out_dir]) print("Sphinx preview docs are available at:") file_url = "file://{}".format(join(out_dir, "index.html")) browser_url = file_url print() print(" {}".format(file_url)) # Serve the current directory for local browsing. Required for MacOS. # N.B. We serve the preview via a HTTP server because it is necessary for # certain browsers (Safari on MacOS, possibly Chrome) due to local file # restrictions. os.chdir(out_dir) sockaddr = ("127.0.0.1", args.port) TCPServer.allow_reuse_address = True httpd = TCPServer(sockaddr, _Handler) http_url = "http://{}:{}/index.html".format(*sockaddr) print() print(" {}".format(http_url)) # Default to using HTTP serving only on MacOS; on Ubuntu, it can spit # out errors and exceptions about broken pipes, 404 files, etc. if sys.platform == "darwin": browser_url = http_url # Try the default browser. if args.browser: webbrowser.open(browser_url) # Wait for server. print() print("Serving and waiting ... use Ctrl-C to exit.") httpd.serve_forever()
from socketserver import TCPServer, StreamRequestHandler, ThreadingMixIn class Server(ThreadingMixIn, TCPServer): pass class Handler(StreamRequestHandler): def handle(self): addr = self.request.getpeername() print('获得连接', addr) self.wfile.write('hellow client'.encode()) server = TCPServer(('', 1234), Handler) server.serve_forever()
def __init__(self, port, host='127.0.0.1', loglevel=logging.WARNING): logger.setLevel(loglevel) self.port = port TCPServer.__init__(self, (host, port), WebSocketHandler)
def __init__(self, port): super(HttpServer, self).__init__() os.chdir("./mp3") self.daemon = True handler = SimpleHTTPRequestHandler self.httpd = TCPServer(("", port), handler)
def handle(self): self.data = self.request.recv(1024).decode('utf-8').strip() print(self.data) request_lines = self.data.split('\r\n') first_line = request_lines[0] verb, path, version = first_line.split(' ') if path == '/': status, response = index() elif path == '/restrito': status, response = restrito() elif path == '/sessao' and verb == 'POST': status, response = login() elif path == '/sessao' and verb == 'DELETE': status, response = logout() else: status = '404 Not Found' response = '<h1>Pagina nao encontrada!</h1>' self.request.sendall("HTTP/1.1 {}\r\n".format(status).encode('utf-8')) self.request.sendall(b"Content-Type: text/html\r\n\r\n") self.request.sendall(response.encode('utf-8')) if __name__ == "__main__": HOST, PORT = "localhost", 8000 TCPServer.allow_reuse_address = True with TCPServer((HOST, PORT), HTTPRequestHander) as server: server.serve_forever()
from socketserver import StreamRequestHandler, TCPServer class TCPHandler(StreamRequestHandler): def handle(self): self.wfile.write("Olá Cliente\n") while True: data = self.rfile.readline().strip().decode("UTF-8") if not data: self.wfile.write(b"Cliente desconectado\n") print(data) if __name__ == "__main__": server_address = ("localhost", 9080) with TCPServer(server_address, TCPHandler) as Server: print("Server Ativo") Server.serve_forever()
from socketserver import TCPServer as TCP, StreamRequestHandler as SRH HOST = '' PORT = 12465 ADDR = (HOST, PORT) class MyRequestHandler(SRH): # 重写handle方法,该方法在基类中没有任何行为,即pass def handle(self): print("连接自:", self.client_address) self.wfile.write(self.rfile.readline()) tcp_ser = TCP(ADDR, MyRequestHandler) print("等待连接...") tcp_ser.serve_forever()
""" 使用socketserver模块创建时间服务器 Version: 0.1 Author: 骆昊 Date: 2018-03-22 """ from socketserver import TCPServer, StreamRequestHandler from time import * class EchoRequestHandler(StreamRequestHandler): def handle(self): currtime = localtime(time()) timestr = strftime('%Y-%m-%d %H:%M:%S', currtime) self.wfile.write(timestr.encode('utf-8')) server = TCPServer(('localhost', 6789), EchoRequestHandler) server.serve_forever()
class EchoHandler(BaseRequestHandler): def handle(self): print('start listining') message = '' mes_len = 0 new_msg = True print('got the connection: {}'.format(self.request)) while True: data = self.request.recv(buffer_size) if new_msg: mes_len = int(data.decode('utf-8')) new_msg = False message += data.decode('utf-8') if len(message) - buffer_size == mes_len: self.request.send(message.encode('utf-8')) print(self.client_address, message) new_msg = True mes_len = 0 message = '' if __name__ == '__main__': server = TCPServer(('', 80), EchoHandler) for i in range(number_of_workers_thread): thread = Thread(target=server.serve_forever) thread.daemon = True thread.start() server.serve_forever()
def __init__(self, port): TCPServer.__init__(self, ("", port), SimpleHTTPRequestHandler) self.process = multiprocessing.Process(target=self.serve_forever)
def thread_job(): print('T1 start\n') cv2.imshow('image',img) while(1): if cv2.waitKey(25) & 0xFF == ord('q'): out.release() cv2.destroyAllWindows() serv.shutdown() break print('T1 finish') if __name__ == '__main__': print("initional socket server...") serv = TCPServer(('192.168.1.11', 80), EchoHandler) print("socket server start!! ") thread1 = threading.Thread(target=thread_job, name='T1') thread1.start() print('all done') serv.serve_forever() #while(1): #if cv2.waitKey(25) & 0xFF == ord('q'): #break #out.release() #cv2.destroyAllWindows()