folder Tahribat.com Forumları
linefolder Java
linefolder [Nodejs] - Emit Kullanımı?



[Nodejs] - Emit Kullanımı?

  1. KısayolKısayol reportŞikayet pmÖzel Mesaj
    lazz
    lazz's avatar
    Kayıt Tarihi: 15/Ekim/2007
    Erkek

    merhaba muritler

    "use strict";
    Object.defineProperty(exports, "__esModule", { value: true });
    const events_1 = require("events");
    const net_1 = require("net");
    const tls = require("tls");
    const Receiver_1 = require("./Receiver");
    const Transmitter_1 = require("./Transmitter");
    const RosException_1 = require("../RosException");
    const debug = require("debug");
    const info = debug('routeros-api:connector:connector:info');
    const error = debug('routeros-api:connector:connector:error');
    /**
     * Connector class responsible for communicating with
     * the routeros via api, sending and receiving buffers.
     *
     * The main focus of this class is to be able to
     * construct and destruct dinamically by the RouterOSAPI class
     * when needed, so the authentication parameters don't
     * need to be changed every time we need to reconnect.
     */
    class Connector extends events_1.EventEmitter {
        /**
         * Constructor which receive the options of the connection
         *
         * @param {Object} options
         */
        constructor(options) {
            super();
            /**
             * Connected status
             */
            this.connected = false;
            /**
             * Connecting status
             */
            this.connecting = false;
            /**
             * Closing status
             */
            this.closing = false;
            this.host = options.host;
            if (options.timeout)
                this.timeout = options.timeout;
            if (options.port)
                this.port = options.port;
            if (typeof options.tls === 'boolean' && options.tls)
                options.tls = {};
            if (typeof options.tls === 'object') {
                if (!options.port)
                    this.port = 8729;
                this.tls = options.tls;
            }
        }
        /**
         * Connect to the routerboard
         *
         * @returns {Connector}
         */
        connect() {
            if (!this.connected) {
                if (!this.connecting) {
                    this.connecting = true;
                    if (this.tls) {
                        this.socket = tls.connect(this.port, this.host, this.tls, this.onConnect.bind(this));
                        this.transmitter = new Transmitter_1.Transmitter(this.socket);
                        this.receiver = new Receiver_1.Receiver(this.socket);
                        this.socket.on('data', this.onData.bind(this));
                        this.socket.on('tlsClientError', this.onError.bind(this));
                        this.socket.once('end', this.onEnd.bind(this));
                        this.socket.once('timeout', this.onTimeout.bind(this));
                        this.socket.once('fatal', this.onEnd.bind(this));
                        this.socket.on('error', this.onError.bind(this));
                        this.socket.setTimeout(this.timeout * 1000);
                        this.socket.setKeepAlive(true);
                    }
                    else {
                        this.socket = new net_1.Socket();
                        this.transmitter = new Transmitter_1.Transmitter(this.socket);
                        this.receiver = new Receiver_1.Receiver(this.socket);
                        this.socket.once('connect', this.onConnect.bind(this));
                        this.socket.once('end', this.onEnd.bind(this));
                        this.socket.once('timeout', this.onTimeout.bind(this));
                        this.socket.once('fatal', this.onEnd.bind(this));
                        this.socket.on('error', this.onError.bind(this));
                        this.socket.on('data', this.onData.bind(this));
                        this.socket.setTimeout(this.timeout * 1000);
                        this.socket.setKeepAlive(true);
                        this.socket.connect(this.port, this.host);
                    }
                }
            }
            return this;
        }
        /**
         * Writes data through the open socket
         *
         * @param {Array} data
         * @returns {Connector}
         */
        write(data) {
            for (const line of data) {
                this.transmitter.write(line);
            }
            this.transmitter.write(null);
            return this;
        }
        /**
         * Register a tag to receive data
         *
         * @param {string} tag
         * @param {function} callback
         */
        read(tag, callback) {
            this.receiver.read(tag, callback);
        }
        /**
         * Unregister a tag, so it no longer waits for data
         * @param {string} tag
         */
        stopRead(tag) {
            this.receiver.stop(tag);
        }
        /**
         * Start closing the connection
         */
        close() {
            if (!this.closing) {
                this.closing = true;
                this.socket.end();
            }
        }
        /**
         * Destroy the socket, no more data
         * can be exchanged from now on and
         * this class itself must be recreated
         */
        destroy() {
            this.socket.destroy();
            this.removeAllListeners();
        }
        /**
         * Socket connection event listener.
         * After the connection is stablished,
         * ask the transmitter to run any
         * command stored over the pool
         *
         * @returns {function}
         */
        onConnect() {
            this.connecting = false;
            this.connected = true;
            info('Connected on %s', this.host);
            this.transmitter.runPool();
            this.emit('connected', this);
        }
        /**
         * Socket end event listener.
         * Terminates the connection after
         * the socket is released
         *
         * @returns {function}
         */
        onEnd() {
            this.emit('close', this);
            this.destroy();
        }
        /**
         * Socket error event listener.
         * Emmits the error while trying to connect and
         * destroys the socket.
         *
         * @returns {function}
         */
        onError(err) {
            err = new RosException_1.RosException(err.errno, err);
            error('Problem while trying to connect to %s. Error: %s', this.host, err.message);
            this.emit('error', err, this);
            this.destroy();
        }
        /**
         * Socket timeout event listener
         * Emmits timeout error and destroys the socket
         *
         * @returns {function}
         */
        onTimeout() {
            this.emit('timeout', new RosException_1.RosException('SOCKTMOUT', { seconds: this.timeout }), this);
            this.destroy();
        }
        /**
         * Socket data event listener
         * Receives the data and sends it to processing
         *
         * @returns {function}
         */
        onData(data) {
            info('Got data from the socket, will process it');
            this.receiver.processRawData(data);
        }
    }
    exports.Connector = Connector;
    
    

    bu şekılde kullanıdıgım bır kutuphane var

    ben burdakı eventlerın ıcınde

    onTimeout() {
            this.emit('timeout', new RosException_1.RosException('SOCKTMOUT', { seconds: this.timeout }), this);
            this.destroy();
        }

    bu kısımdakı olayı yakalamak ıstıyorum

    bu dılden pek anlamıyorum ama

    asagıdakı sekılde kodları kullanıyorum

    const RouterOSAPI = require("node-routeros").RouterOSAPI;
    
    Mikrotik=new RouterOSAPI({host:'123.123.123',
                              user:'test',
                              password:'test1',
                              keepalive:true
    });
    Mikrotik.connect().then(() => {
      Mikrotik.write("/interface/print").then((data) => {
        console.log(data)
      }).catch((err) => {
        console.log('Komut Çalışmadı')
        console.log(err)
      });
    }).catch((err) => {
      console.log('Baglantı Saglanamadı')
      console.log(err)
    });

     

    şimdi ben burada Mikrotik.connect() kullanabılıyorum fakat

    Mikrotik.onTimeout()

    seklınde kullanamıyorum bunun sebebı nedır  => Fonksiyon degıl hatası veriyor.

    birde ben 

    Mikrotik.write("/interface/print")

    bu fonksiyon kullanabılmek için surekli

    connectin içindemi kalmam lazım

    lazz tarafından 30/Nis/20 13:04 tarihinde düzenlenmiştir
  2. KısayolKısayol reportŞikayet pmÖzel Mesaj
    MhmdAlmz
    MhmdAlmz's avatar
    Kayıt Tarihi: 09/Ağustos/2015
    Erkek

    Hocam socketi ya dinlersin yada mesaj gönderirsin.

     

    Gönderdiğin mesaj da bir şablon ile gönderilir. Başlığı olur methodun ismi datası vs vs ..

    Bu durumda dinlerken

    SocketBey.bakBenSeniDinliyom("DinlediğimMethodBu",dataGelirsedeBunuYap);

    const dataGelirsedeBunuYap=function(gelenData){

    }

     

    şeklinde kodlaman gerekiyor. Yani method isimleri birer constant enum artık ne dersen.


    Andolsun kuşluk vaktine ve dindiği zaman o geceye ki, Rabbin sana veda etmedi ve darılmadı! Ve kesinlikle senin için sonu önünden (ahiret dünyadan) daha hayırlıdır. ileride Rabbin sana verecek de hoşnut olacaksın! O, seni bir yetim iken barındırmadı mı? Seni, yol bilmez iken (doğru) yola koymadı mı? Seni bir yoksul iken zengin etmedi mi? Öyle ise, sakın yetime kahretme (onu horlama)! El açıp isteyeni de azarlama! Fakat Rabbinin nimetini anlat da anlat!
  3. KısayolKısayol reportŞikayet pmÖzel Mesaj
    lazz
    lazz's avatar
    Kayıt Tarihi: 15/Ekim/2007
    Erkek

    hocam dedıklerınden  asagıdakı kodu anladım. ama yanlıs anladım galiba calısmadı :(

    Mikrotik.on("onConnect",function() {
    	console.log("Oldumu");
    });

    bu sekılde bu kutuphanade 

    onTimeout()

    olayını nasıl yakalıyabnılırım bılale anlatır gıbı anlatabılırsen sevınırım :)

  4. KısayolKısayol reportŞikayet pmÖzel Mesaj
    RockZs
    RockZs's avatar
    Kayıt Tarihi: 30/Haziran/2002
    Erkek

    Bağlantıyı sağladıktan sonra onTimeout() u çağırmayı denesen. Yani:

    Mikrotik.connect().then(() => {

    Buranın içinde onTimout u çağırsan?

    });

    bir de catch(err) kullanmışsın, böyle kullandığını bilmiyordum, başında try() olması gerekmiyor sanırım değil mi?

    RockZs tarafından 30/Nis/20 14:03 tarihinde düzenlenmiştir
  5. KısayolKısayol reportŞikayet pmÖzel Mesaj
    lazz
    lazz's avatar
    Kayıt Tarihi: 15/Ekim/2007
    Erkek
    RockZs bunu yazdı

    Bağlantıyı sağladıktan sonra onTimeout() u çağırmayı denesen. Yani:

    Mikrotik.connect().then(() => {

    Buranın içinde onTimout u çağırsan?

    });

    gene hata verıyor hocam

    anladıgım kadarıyla bu kutphanenın ıcınde 

    .on kullanarak eventler olusturulmus 

     

    this.socket.on('error', this.onError.bind(this));

     seklınde adamlar burdan hata olustumu kendılerı anlıyolar, ama ben araya gırıp nasıl anlarım daha ayıkamadım.

    hata olayıda aslında orda hata yakalamıyor o komut sync calıstıgı ıcın hata olusutrsa oraya gelıyo ıslem olusmass then ıcıne gıdıyor :)

    en azından o sekılde gordum adamların kodlarından

  6. KısayolKısayol reportŞikayet pmÖzel Mesaj
    RockZs
    RockZs's avatar
    Kayıt Tarihi: 30/Haziran/2002
    Erkek

    Anladım. Gelen hatayı da burada paylaşırsan iyi olabilir.

    Hızlı çözüm olarak, işini görecekse 

    onTimeout() {


    this.emit('timeout', new RosException_1.RosException('SOCKTMOUT', { seconds: this.timeout }), this);

    buralara da kod yazabilirsin..

    this.destroy();


    }

  7. KısayolKısayol reportŞikayet pmÖzel Mesaj
    lazz
    lazz's avatar
    Kayıt Tarihi: 15/Ekim/2007
    Erkek
    RockZs bunu yazdı

    Anladım. Gelen hatayı da burada paylaşırsan iyi olabilir.

    Hızlı çözüm olarak, işini görecekse 

    onTimeout() {


    this.emit('timeout', new RosException_1.RosException('SOCKTMOUT', { seconds: this.timeout }), this);

    buralara da kod yazabilirsin..

    this.destroy();


    }

    oraya yazdıgımda hıcbırsey yakalayamıyorum hocam

    aldıgım hatalar hep kutuphaneden donen cevaplar ornek

    Error: no such command
        at Channel.once (/root/MikroNode/node_modules/node-routeros/dist/Channel.js:69:52)
        at Object.onceWrapper (events.js:286:20)
        at Channel.emit (events.js:198:13)
        at Channel.processPacket (/root/MikroNode/node_modules/node-routeros/dist/Channel.js:116:18)
        at Object.connector.read [as callback] (/root/MikroNode/node_modules/node-routeros/dist/Channel.js:98:55)
        at Receiver.sendTagData (/root/MikroNode/node_modules/node-routeros/dist/connector/Receiver.js:246:17)
        at process (/root/MikroNode/node_modules/node-routeros/dist/connector/Receiver.js:209:34)
        at Receiver.processSentence (/root/MikroNode/node_modules/node-routeros/dist/connector/Receiver.js:235:13)
        at Receiver.processRawData (/root/MikroNode/node_modules/node-routeros/dist/connector/Receiver.js:164:26)
        at Connector.onData (/root/MikroNode/node_modules/node-routeros/dist/connector/Connector.js:198:23)

    bu sekılde

  8. KısayolKısayol reportŞikayet pmÖzel Mesaj
    RockZs
    RockZs's avatar
    Kayıt Tarihi: 30/Haziran/2002
    Erkek

    Anladım. onTimeout bir event olduğundan bir yerde çağırılabilecek birşey olmaması lazım. fakat bahsettiğim yere

    console.log("xyz")

    yazdığında onTimeout yani zaman aşımı olması durumunda console a xyz yazması lazım.

    Amacın timeout olduğunda ekstradan birşey yaptırmak ise bence oraya yazılabilir.

    Diğer türlü zaten onTimeout hiç çağrılmıyordur. Birşey yakalanmamasının nedeni ontimeout un aslında hiç çağrılmaması, bu olayın hiç meydana gelmemesi olabilir mi?

  9. KısayolKısayol reportŞikayet pmÖzel Mesaj
    MhmdAlmz
    MhmdAlmz's avatar
    Kayıt Tarihi: 09/Ağustos/2015
    Erkek

    Hocam oradaki onTimeOut methodunun ismine bak. Muhtemelen ismini yanlış yazıyorsundur.

    Mesela socket_on_time_out olabilir,  ontimeout olabilir, _onTimeOut olabilir. vs vs .

     

    Sorun bundan kaynaklanıyodur. Yok mu örneği hocam kütüphane içinde ?


    Andolsun kuşluk vaktine ve dindiği zaman o geceye ki, Rabbin sana veda etmedi ve darılmadı! Ve kesinlikle senin için sonu önünden (ahiret dünyadan) daha hayırlıdır. ileride Rabbin sana verecek de hoşnut olacaksın! O, seni bir yetim iken barındırmadı mı? Seni, yol bilmez iken (doğru) yola koymadı mı? Seni bir yoksul iken zengin etmedi mi? Öyle ise, sakın yetime kahretme (onu horlama)! El açıp isteyeni de azarlama! Fakat Rabbinin nimetini anlat da anlat!
Toplam Hit: 1707 Toplam Mesaj: 9
nodejs mikronode