def main(args): parser = ArgumentParser() parser.add_argument("-p", "--port", default=8080, type=int, help="Port to listen on.") args = parser.parse_args() WEBMUX_STATIC_PATH = os.path.join(webmux.__path__[0], "static") root = Home() static_path = resource.Resource() static_path.putChild("css", static.File(WEBMUX_STATIC_PATH + "/css")) static_path.putChild("js", static.File(WEBMUX_STATIC_PATH + "/js")) static_path.putChild("img", static.File(WEBMUX_STATIC_PATH + "/img")) root.putChild("terminal", SockJSResource(TerminalFactory)) root.putChild("signup", Signup()) root.putChild("login", Login()) root.putChild("logout", Logout()) root.putChild("static", static_path) site = server.Site(root) site.sessionFactory = LongSession reactor.listenTCP(args.port, site) reactor.callLater(0, init) reactor.run()
def status(self, request): #cors.config_cors(request) options = { 'websocket': True, 'heartbeat': 5, 'timeout': 2, } return SockJSResource(StatusSockJSFactory(self.system_status), options)
def logs(self, request, name): #cors.config_cors(request) options = { 'websocket': True, 'heartbeat': 5, 'timeout': 2, } return SockJSResource(LogSockJSFactory(name), options)
def get_resource(self): www_root = os.path.split(self.workroot)[0] wwwroot = os.path.join(www_root, 'wwwroot') swagger = os.path.join(www_root, 'swagger') r = RootResource(self) r.putChild("v1", RestResource()) r.putChild("chat", SockJSResource(Factory.forProtocol(SSHProtocol))) r.putChild("console", File(wwwroot)) r.putChild("swagger", File(swagger)) return r
def createEndpoint(self, name, options=None): endpoint = Endpoint(name) if options is None: options = {'encoding': 'utf-8'} self.resource.putChild( name, SockJSResource( EndpointFactory.forProtocol(EndpointProtocol, endpoint), options)) return endpoint
def startService(self): MultiService.startService(self) staticPath = FilePath(__file__).sibling("static") root = NoListDirFile(staticPath.path) root.putChild('api', SockJSResource(Factory.forProtocol(DaneDoctorProtocol))) webService = StreamServerEndpointService( serverFromString(self._reactor, "tcp:8080"), Site(root)) webService.setServiceParent(self)
def init(deejayd_core, config, webui_logfile, htdocs_dir): # main handler main_handler = DeejaydMainHandler() # json-rpc handler main_handler.putChild("rpc", SockJSResource(DeejaydFactory(deejayd_core))) for d in ('dist', 'ressources'): path = os.path.join(htdocs_dir, d) main_handler.putChild(d, static.File(path)) root_url = config.get('webui', 'root_url') root_url = root_url[-1] == '/' and root_url or root_url + '/' if root_url == '/': root = main_handler else: root = DeejaydRootRedirector(root_url, main_handler) return SiteWithCustomLogging(root, logPath=webui_logfile)
def __init__(self, static_path, templates_path): resource.Resource.__init__(self) self.log = logging.getLogger('webui.core') for action in 'online', 'offline', 'scan': self.putChild(action, WebUIAction(self, 'nm_{}'.format(action))) if not isinstance(static_path, FilePath): static_path = FilePath(static_path) for p in static_path.listdir(): self.putChild(p, File(static_path.child(p).path)) if not isinstance(templates_path, FilePath): templates_path = FilePath(templates_path) self.templates = jinja2.Environment( loader=jinja2.FileSystemLoader(templates_path.path)) self.templates.filters['json'] = self.jinja2_json self.templates.filters['unless_false'] = self.jinja2_unless_false self.events = ClientEvents(self.handle_command) self.putChild('events', SockJSResource(self.events))
def __init__(self, static_path, templates_path): resource.Resource.__init__(self) self.log = logging.getLogger("webui.core") for action in b"online", b"offline", b"scan": self.putChild(action, WebUIAction(self, "nm_{}".format(action))) if not isinstance(static_path, FilePath): static_path = FilePath(static_path) for p in static_path.listdir(): self.putChild(bytes(p), File(static_path.child(p).path)) if not isinstance(templates_path, FilePath): templates_path = FilePath(templates_path) self.templates = jinja2.Environment( loader=jinja2.FileSystemLoader(templates_path.path) ) self.templates.filters["json"] = self.jinja2_json self.templates.filters["unless_false"] = self.jinja2_unless_false self.events = ClientEvents(self.handle_command) self.putChild("events", SockJSResource(self.events))
if self.socket.transport: self.socket.transport.loseConnection() class GameProtocol(protocol.Protocol): def connectionMade(self): self.is_initialized = False def dataReceived(self, message): if self.is_initialized: self.process.transport.write(message.encode('ascii') + '\n') else: game_id = message if int(game_id) not in game_manager.get_valid_game_ids(): self.close() return self.process = GameProcessProtocol(self) reactor.spawnProcess(self.process, 'java', [ 'java', '-cp', game_manager.get_class_path(game_id), game_manager.get_class_name(game_id) ]) self.is_initialized = True def connectionLost(self, reason): if self.process.active: self.process.transport.signalProcess('KILL') game_resource = SockJSResource(protocol.Factory.forProtocol(GameProtocol))
sensor.OnlineProtocol = online reactor.listenTCP(int(config.listen_port), sensor) # 把工厂和端口进行绑定 node = NodeFactory("NodeFactory", NodeProtocol) node.OnlineProtocol = online reactor.listenTCP(int(config.slave_port), node) rpc_point = endpoints.TCP4ServerEndpoint(reactor, int(config.rpc_port)) rpc_point.listen(server.Site(Rpc)) # 把资源和对应的端口进行绑定 send_data = SendUiFactory("SendUiFactory", SendUiProtocol) send_data.OnlineProtocol = online send_js = SensorFactory('SensorJSFactory', NodeInfoUiProtocol) # 展示结点状态 send_js.OnlineProtocol = online send_work = SensorFactory('SensorJSFactory', NodeUiProtocol) send_work.OnlineProtocol = online root = resource.Resource() TaskDispatch.OnlineProtocol = online root.putChild('show_data', SockJSResource(send_data)) root.putChild("post_data", NodePage()) root.putChild('show_job', SockJSResource(send_work)) root.putChild('show_js', SockJSResource(send_js)) # 接收js 数据并把结点的状态显示在网页上 site = server.Site(root) reactor.listenTCP(int(config.ui_port), site) reactor.run()
def __init__(self, options=None): SockJSResource.__init__(self, PubSubFactory(self), options)
def __init__(self, options=None): SockJSResource.__init__(self, MultiplexFactory(self), options)
close = CloseFactory() s = SockJSMultiFactory() s.addFactory(echo, "echo", {'streaming_limit': 4 * 1024}) s.addFactory(close, "close", {'streaming_limit': 4 * 1024}) s.addFactory(echo, "disabled_websocket_echo", { 'websocket': False, 'streaming_limit': 4 * 1024 }) s.addFactory(echo, "cookie_needed_echo", { 'cookie_needed': True, 'streaming_limit': 4 * 1024 }) root = resource.Resource() root.putChild("echo", SockJSResource(echo, {'streaming_limit': 4 * 1024})) root.putChild("close", SockJSResource(close, {'streaming_limit': 4 * 1024})) root.putChild( "disabled_websocket_echo", SockJSResource(echo, { 'websocket': False, 'streaming_limit': 4 * 1024 })) root.putChild( "cookie_needed_echo", SockJSResource(echo, { 'cookie_needed': True, 'streaming_limit': 4 * 1024 })) site = server.Site(root)
from hendrix.contrib. async .messaging import hxdispatcher from hendrix.deploy.base import HendrixDeploy from txsockjs.factory import SockJSResource from hendrix.contrib. async .resources import MessageHandlerProtocol from hendrix.facilities.resources import NamedResource from twisted.internet.protocol import Factory message_resource = NamedResource('hendrix-demo') message_resource.putChild( 'messages', SockJSResource(Factory.forProtocol(MessageHandlerProtocol))) from twisted.conch.telnet import TelnetTransport, TelnetProtocol from twisted.internet.protocol import ServerFactory class TelnetToWebsocket(TelnetProtocol): def dataReceived(self, data): hxdispatcher.send('noodly_messages', data) telnet_server_factory = ServerFactory() telnet_server_factory.protocol = lambda: TelnetTransport(TelnetToWebsocket) deployer = HendrixDeploy(options={'wsgi': 'hendrix_demo.wsgi.application'}) deployer.resources.append(message_resource) deployer.reactor.listenTCP(6565, telnet_server_factory) deployer.run()
from twisted.internet import reactor from onlineProtocol import online from factory_protocol.protocol.sensorprotocol import SensorProtocol from factory_protocol.factory.sensorfactory import SensorFactory from factory_protocol.protocol.SendUi import SendUiProtocol from factory_protocol.factory.SendUiFactory import SendUiFactory from stateRPC import Rpc from twisted.web import resource, server from txsockjs.factory import SockJSResource from twisted.internet import endpoints from config import config sensor = SensorFactory('SensorFactory', SensorProtocol) sensor.OnlineProtocol = online reactor.listenTCP(int(config.listen_port), sensor) # 把工厂和端口进行绑定 rpc_point = endpoints.TCP4ServerEndpoint(reactor, int(config.rpc_port)) rpc_point.listen(server.Site(Rpc)) # 把资源和对应的端口进行绑定 send_data = SendUiFactory("SendUiFactory", SendUiProtocol) send_data.OnlineProtocol = online root = resource.Resource() root.putChild('show_data', SockJSResource(send_data)) site = server.Site(root) reactor.listenTCP(int(config.ui_port), site) reactor.run()
import os from twisted.internet import reactor from twisted.internet.protocol import Factory from twisted.web import server from twisted.web.static import File from txsockjs.factory import SockJSResource from core.terminal import SSHProtocol workroot = os.path.dirname(os.path.abspath(__file__)) wwwroot = os.path.split(workroot)[0] wwwroot = os.path.join(wwwroot, "wwwroot") root = File(wwwroot) root.putChild("chat", SockJSResource(Factory.forProtocol(SSHProtocol))) site = server.Site(root) reactor.listenTCP(9002, site) reactor.run()
def publish(self, channel, message, error=False): if channel in self.channels: for p in self.channels[channel]: if error: p.errorReceived(channel, message) else: p.messageReceived(channel, message) # Start the party shutil.rmtree("./tmp") os.mkdir("./tmp") index_page = File("index.html") index_page.putChild("sockjs", SockJSResource(TumblrServer())) index_page.putChild("archives", File("archives")) from functools import partial def bypass(self, path, request): return self index_page.getChild = partial(bypass, index_page) def resource(): return index_page
log.startLogging(sys.stdout) if options.server: # Listen for incoming TCP connections print("Listening for incoming TCP connections on port %d" % options.port) daemon.listen(options.port) # Serve files from web root = File(r"web") root.putChild(b"", File('web/main.html')) root.putChild(b"monitor", WebMonitor(factory=daemon, object=obj)) if options.passwd_file and os.path.exists(options.passwd_file): site = Site(Auth(root, options.passwd_file)) else: site = Site(root) # WebSockets if _HAVE_TXSOCKJS: ws = SimpleFactory(WSProtocol, obj) obj['ws'] = ws root.putChild(b"ws", SockJSResource(ws)) # Database connection obj['db'] = DB(dbhost=options.db_host) obj['db_status_timestamp'] = datetime.datetime.utcfromtimestamp(0) print("Listening for incoming HTTP connections on port %d" % options.http_port) TCP4ServerEndpoint(daemon._reactor, options.http_port).listen(site) daemon._reactor.run()
del self.factory.connections[self] class BroadcastFactory(protocol.Factory): protocol = Broadcast connections = {} echo = EchoFactory() close = CloseFactory() ticker = TickerFactory() amplify = AmplifyFactory() broadcast = BroadcastFactory() sockjs_root = resource.Resource() sockjs_root.putChild("echo", SockJSResource(echo, {'streaming_limit': 4 * 1024})) sockjs_root.putChild("disabled_websocket_echo", SockJSResource(echo, {'websocket': False})) sockjs_root.putChild("cookie_needed_echo", SockJSResource(echo, {'cookie_needed': True})) sockjs_root.putChild("close", SockJSResource(close)) sockjs_root.putChild("ticker", SockJSResource(ticker)) sockjs_root.putChild("amplify", SockJSResource(amplify)) sockjs_root.putChild("broadcast", SockJSResource(broadcast)) sockjs = server.Site(sockjs_root) ### SSL shenanigans # A direct copy of DefaultOpenSSLContextFactory as of Twisted 12.2.0 # The only difference is using ctx.use_certificate_chain_file instead of ctx.use_certificate_file