node.js Socketio和动态内容

时间:2015-06-03 13:05:47

标签: javascript jquery html node.js socket.io

我正在尝试这样做,以便当nodejs在irc聊天中触发某个内容时,html页面(在*:3000上运行)将执行某些JavaScript。当我尝试实现这一点时,它会运行代码,但不会执行showDiv();

我在chrome中使用localhost:3000打开它。

当我输入时,为什么ID为“welcome”的div不会变为可见!跟随正在拾取的IRC。

完整代码:

的index.html:

<!doctype html>
<html>
  <head>
    <title>Family Fortunes</title>
    <style>
      * { margin: 0; padding: 0; box-sizing: border-box; }
      body { font: 13px Helvetica, Arial; }
      form { background: #000; padding: 3px; position: fixed; bottom: 0; width: 100%; }
      form input { border: 0; padding: 10px; width: 90%; margin-right: .5%; }
      form button { width: 9%; background: rgb(130, 224, 255); border: none; padding: 10px; }
      #messages { list-style-type: none; margin: 0; padding: 0; }
      #messages li { padding: 5px 10px; }
      #messages li:nth-child(odd) { background: #eee; }
      #welcome {display:none;}
    </style>
    <script>
      var socket = io();
         function showDiv() {
                document.getElementById('welcome').style.display = "visible";
        }  
    </script>
    <script src="https://cdn.socket.io/socket.io-1.2.0.js"></script>
    <script src="http://code.jquery.com/jquery-1.11.1.js"></script>
  </head>
  <body>
<button onclick="showDiv()">Click me</button>
<div id="welcome"> WELCOME</div>



  <script src="/socket.io/socket.io.js"></script>  
  <script src="example.js"></script>
  </body>
</html>

Example.js:

//http://www.schmoopiie.com/docs/twitch-irc/Commands/Action

//SOCKET.IO Setup
var io = require('socket.io')(http);
var app = require('express')();
var http = require('http').Server(app);

io.on('connection', function(socket){
  console.log('a user connected');
  socket.on('disconnect', function(){
    console.log('user disconnected');
  });
});
http.listen(3000, function(){
  console.log('listening on *:3000');
});

app.get('/', function(req, res){
  res.sendfile('index.html');
});

//Node.JS Setup
var irc = require('twitch-irc');
var api = require('twitch-irc-api');

//Declare Global Variable with NO attributes.
var Follower = {};
var LastFollower = {};

//API Callout
setInterval(function(){ 
    api.call({
        channel: null,
        method: 'GET',
        path: '/channels/greatbritishbg/follows',
        options: {
            limit: 1,
            offset: 0
        }
    }, function(err, statusCode, response) {
        if (err) {
            console.log(err);
            return;
        }
            Follower.response = String(response.follows[0].user.display_name);
            //console.log('Returning Current follower Loop: ' + Follower.response);
    });
}, 1000);

//IRC Connect
var clientOptions = {
    options: {
        debug: true,
        debugIgnore: ['ping', 'chat', 'action']
    },
    identity: {
        username: 'greatbritishbg',
        password: 'oauth:'
    },
    channels: ['greatbritishbg']
}
var client = new irc.client(clientOptions);
client.connect();

function showDiv() {
        document.getElementById('welcome').style.display = "visible";
}  

//Commands
client.addListener('chat', function (channel, user, message) {
    console.log(user.username + ': ' + message);
    if (message.toLowerCase() === '!follow') {
        client.say(channel, 'Latest Follower: ' + Follower.response).then(function() {
        showDiv();
        });
    }
});

3 个答案:

答案 0 :(得分:1)

我认为你在NodeJS服务器端脚本之间感到困惑, 和JS客户端。

您不能直接从客户端直接调用“example.js”,这是您的服务器端脚本。

您必须将其作为NodeJS http服务器启动,基本上使用终端中的node命令进行开发(在生产中,可能使用foreverjs):

Linux / OS X:

cd /path/to/your/project/folder
node example.js

视窗:

dir \path\to\your\project\folder
node example.js

然后,在此服务器端脚本上,您必须触发您感兴趣的websockets事件。 (注意初始化的顺序:io应该在http服务器之后初始化)

例如,您可emit全局io.emit(eventName, arguments) 或者您也可以在emit namespace事件中收到emit socket,甚至io一个connectionsocket.emit(eventName, arguments)

eventName应该是客户端JS将侦听的字符串

arguments可以是您想要的任何内容

The documentation overview of socket.io充满了非常好的例子。

示例:

服务器侧

// Send it to a specific socket
var sockets = {};
var id = 0;

io.on('connection', function (socket) {
    // Manage something with the socket
    clients.push({
        id: id++,
        socket: socket
    });
});

// And when an internal server-side thing happens...

followersManager.on('connection', function (followerName) {
    // Find the given socket in any way
    var socket = clients.find(function (client) {
        return client.id == 1;
    }, this);
    // Then use this special socket
    socket.emit('followers.new', followerName);
});

// Note that Array.prototype.find is an experimental feature of ES6.
// It can be easily fixed with the polyfill for oldest versions:
require('array.prototype.find');

// OR you can also emit it to all connected sockets
var followerName = 'Foo';
io.emit('followers.new', followerName);

请记住,在服务器端,您无法调用客户端功能!

然后,在客户端(应该是example.js之外的另一个文件),您只需要监听这个给定的事件:

<强>客户端

function showDiv() {
    document.getElementById('welcome').style.display = "visible";
}

var socket = io();
socket.on('followers.new', function (followerName) {
    showDiv();
    // Do something with eventual arguments here, such as retrieve a new follower's name and append it to a list...
    alert('New follower: ' + followerName);
}

答案 1 :(得分:0)

我认为你做了很多错事,但我会尽力帮助你提供一些建议。

首先,我没有以正确的方式启动socket.io。

// This code is on server
// Create express app
var app = require('express')();
// Get http server
var server = require('http').Server(app);
// Create socket.io server
var io = require('socket.io')(server);

其次,您不在服务器上发出socket.io事件 对我来说,你必须在客户端监听器中执行此操作

// This code is on server
// To send an event from server to client you have to use io
io.emit('follow');

第三,您没有在客户端上收到活动

// This code is on client
// To receive an event on client you have to use object return by io
var socket = io();
socket.on('follow', function() {
  showDiv();
}

答案 2 :(得分:-1)

确保div #welcome的CSS没有

visibility: hidden;

简单地将其显示为块将无法正常工作,因为它实际上仍然隐藏在CSS中。

如果它被隐藏,那么您可以在Javascript中添加另一行:

function showDiv() {
    document.getElementById('welcome').style.display = "block";
    document.getElementById('welcome').style.visibility = "visible";
}  

同时检查高度和宽度是否设置等。