在脚本范围内使用函数?

时间:2018-01-03 13:53:35

标签: javascript node.js function web-services websocket

尝试使用node.js的ws库,但我整个上午一直在努力解决问题。

这是我目前的代码:

var MySQLEvents = require('mysql-events');
const WebSocket = require('ws');

const wss = new WebSocket.Server({ port: 8080 });

wss.on('connection', function (ws) {
  ws.on('message', function (message) {
    console.log('received: %s', message)
  })

  ws.send("hey mane");

})

var dsn = {
  host:     'localhost',
  user:     'root',
  password: ''
};
var myCon = MySQLEvents(dsn);

var event1 = myCon.add(
  'db.test.name.value',
  function (oldRow, newRow, event) {
    if (oldRow !== null && newRow !== null) {
      console.log("DB change")
    }
  }, 
  'Active'
);

var MySQLEvents = require('mysql-events');
var dsn = {
  host:     'localhost',
  user:     'root',
  password: '',
};
var mysqlEventWatcher = MySQLEvents(dsn);
var watcher =mysqlEventWatcher.add(
  'experimental.test',
  function (oldRow, newRow, event) {
      console.log(event);
     //row inserted 
    if (oldRow === null) {
      console.log("Row inserted");
    }

     //row deleted 
    if (newRow === null) {
      console.log("Row deleted");
    }

     //row updated 
    if (oldRow !== null && newRow !== null) {
        console.log("Row updated");
    }

    //detailed event information 
    //console.log(event);
  }, 

);

注意这部分代码:

wss.on('connection', function (ws) {
  ws.on('message', function (message) {
    console.log('received: %s', message)
  })

  ws.send("hey mane");

})

这里创建了一个名为ws的函数,但对我来说问题是它只能在这个小代码括号中使用它。我希望在代码中进一步向下ws.send('hello');,但是会显示一条错误,表示未定义ws。如何让ws在整个脚本中工作?

更新: 我希望ws.send就在这里:

//row inserted 
    if (oldRow === null) {
      **HERE**
    }

     //row deleted 
    if (newRow === null) {
      **HERE**
    }

     //row updated 
    if (oldRow !== null && newRow !== null) {
        **HERE**


}

客户端

url = "ws://localhost:8080";
ws = new WebSocket(url);

// event emmited when connected
    ws.onopen = function () {
        console.log('websocket is connected ...');
        // sending a send event to websocket server
        ws.send('connected');
    }
    // event emmited when receiving message 
    ws.onmessage = function (ev) {
        console.log(ev.data);
    }

1 个答案:

答案 0 :(得分:0)

如果您要将数据发送给每个已连接的用户(您现在在评论中说明),那么ws doc here中就有一个示例。您迭代wss.clients并发送到每个连接的客户端:

  wss.clients.forEach(function each(client) {
    if (client.readyState === WebSocket.OPEN) {
      client.send(data);
    }
  });