문제

I want to create something like this: system_example

And i didn't know, how to create "client in server" in Twisted, for send response to another server. I mean sheme:
for example, it was been write some file into fs1:
Client -> Server -> FSClient(created into Server.onMessage()) -> Fileserver
and get response:
Fileserver -> FSClient -> Server -> Client

client.py:

ADDRESS = '127.0.0.1'
PORT = 5000

import os
import time
from random import shuffle
from twisted.internet import reactor
from autobahn.websocket import WebSocketClientFactory, WebSocketClientProtocol, connectWS

class DFSClientProtocol(WebSocketClientProtocol):

    def onOpen(self):
        text_files = [f for f in os.listdir(".\\initial") if f.endswith('.txt')]

        # write data into DFS
        shuffle(text_files)
        for file_name in text_files:
            file_path = str(".\\initial\\"+file_name)
            f = open(file_path, 'r')
            message = '[W]['+file_name+']'+f.read()
            self.sendMessage(message)
            f.close()

        # read from DFS
        shuffle(text_files)
        for file_name in text_files:
           message = '[R]['+file_name+']'
           self.sendMessage(message)

    def onMessage(self, msg, binary):
        typeMsg = msg[:3]
        file_name = msg[4:16]
        if typeMsg == '[C]':
            message = msg[17:]
            file_path = str(".\\read\\"+file_name)
            f = open(file_path, 'w')
            f.write(message)
            f.close()

if __name__ == '__main__':
    factory = WebSocketClientFactory("ws://" + ADDRESS + ":" + str(PORT), debug = False)
    factory.protocol = DFSClientProtocol
    connectWS(factory)
    print 'connecting to %s port %s' % (ADDRESS, PORT)
    reactor.run()

server.py (and fileserver-client):

ADDRESS = '127.0.0.1'
PORT = 5000
OPERATION = ''
SERVERS = 0
FILES = {}
SERVERS_PORT = [5001, 5002, 5003, 5004]
SERVER_FILEDIRS = ('fs1', 'fs2', 'fs3', 'fs4')
BYTES = [0, 0, 0, 0]

import time
from socket import gethostbyaddr
from twisted.internet import reactor
from autobahn.websocket import WebSocketServerFactory, WebSocketServerProtocol, listenWS, WebSocketClientFactory, WebSocketClientProtocol, connectWS

class FSClient(WebSocketClientProtocol):

    def onOpen(self):
        # send request to Fileserver
        self.sendMessage(OPERATION)

    def onMessage(self, msg, binary):
        # get response from Fileserver and resend to Server
        self.sendMessage(msg)


class DFS(WebSocketServerProtocol):

    def onOpen(self):
        peer = self.transport.getPeer()
        print "[USER][%s] User with %s connected" % (time.strftime("%H:%M:%S"), peer)

    def connectionLost(self, reason):
        print '[USER][%s] Lost connection from %s' % (time.strftime("%H:%M:%S"), self.transport.getPeer())

    def onMessage(self, msg, binary):
        typeMsg = msg[:3]
        file_name = msg[4:16]
        if typeMsg == '[W]':
            print "[W][%s] Write %s file into DFS" % (time.strftime("%H:%M:%S"), file_name)
            # at this place i want to send request to FSClient and this object send request for Fileserver
            # Client -> Server -> FSClient -> Fileserver
            # and when fileserver doing somework, he send response by sheme:
            # Fileserver -> FSclient -> Server -> Client 
        elif typeMsg == '[R]':
            print "[R][%s] Read %s file from DFS" % (time.strftime("%H:%M:%S"), file_name)

if __name__ == '__main__':
    import sys
    if len(sys.argv)<2:
        sys.exit("Using server.py [SERVERS]")
    factory = WebSocketServerFactory("ws://" + ADDRESS + ":" + str(PORT), debug = False)
    SERVERS = int(sys.argv[1])
    factory.protocol = DFS
    listenWS(factory)
    print 'Server starting up on %s port %s' % (ADDRESS, PORT)
    reactor.run()

fileserver.py:

ADDRESS = '127.0.0.1'
PORT = 5001
CATALOG_NAME = ''
FILES_PATH = ''

import time
from socket import gethostbyaddr
from twisted.internet import reactor
from autobahn.websocket import WebSocketServerFactory, WebSocketServerProtocol, listenWS

class FS(WebSocketServerProtocol):

    def onOpen(self):
        peer = self.transport.getPeer()
        print "[USER][%s] User with %s connected" % (time.strftime("%H:%M:%S"), peer)

    def connectionLost(self, reason):
        print '[USER][%s] Lost connection from %s' % (time.strftime("%H:%M:%S"), self.transport.getPeer())

    def onMessage(self, msg, binary):
        typeMsg = msg[:3]
        file_name = msg[4:16]
        if typeMsg == '[W]':
            print "[W][%s] Write %s file into %s" % (time.strftime("%H:%M:%S"), file_name, CATALOG_NAME)
            message = msg[17:]
            file_path = FILES_PATH + file_name
            f = open(file_path, 'w')
            f.write(message)
            f.close()
            print "File %s successfully writen..." % file_name
            self.sendMessage('[C]['+file_name+']OK')
        elif typeMsg == '[R]':
            print "[R][%s] Read %s file from %s" % (time.strftime("%H:%M:%S"), file_name, CATALOG_NAME)
            print "File %s successfully read..." % file_name
            file_path = FILES_PATH + file_name
            f = open(file_path, 'r')
            message = '[O]['+file_name+']' + f.read()
            f.close()
            self.sendMessage(message)

if __name__ == '__main__':
    import sys
    if len(sys.argv)<4:
        sys.exit("Using fileserver.py [IP] [PORT] [file_catalog_name]")
    ADDRESS = str(sys.argv[1])
    PORT = int(sys.argv[2])
    CATALOG_NAME = str(sys.argv[3])
    FILES_PATH = '.\\data\\' + CATALOG_NAME + '\\'
    factory = WebSocketServerFactory("ws://" + ADDRESS + ":" + str(PORT), debug = False)
    factory.protocol = FS
    listenWS(factory)
    print 'Server starting up on %s port %s' % (ADDRESS, PORT)
    reactor.run()
도움이 되었습니까?

해결책

The short version, for the forwarding WebSocket in a WebSocket server to another server again over WebSocket: in DFS, create a new WebSocketClientFactory and call connectWs in DFS.onOpen. You probably don't want to establish a new forwarding WebSocket connection upon each and every WebSocket message coming in to DFS.

This is only if I get what you want to do: see, it's good that you posted code (otherwise I had been completely clueless), but it would be also good to better describe what you actually trying to achieve - high-level.

라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top