簡體   English   中英

node.js Socketio和動態內容

[英]node.js Socketio and dynamic content

我試圖做到這一點,以便當nodejs在irc聊天中觸發某些內容時,html頁面(在*:3000上運行)將執行一些JavaScript。 當我嘗試實現此目標時,它將運行代碼,但不執行showDiv();。

我在localhost:3000打開的chrome中運行它。

當我在正在拾取的IRC中鍵入!follow時,為什么id為“ welcome”的div不會變為可見。

完整代碼:

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();
        });
    }
});

我認為您在NodeJS服務器端腳本和JS客戶端腳本之間感到困惑。

您不能直接從客戶端直接調用服務器端腳本“ example.js”。

您必須將其作為NodeJS http服務器啟動,基本上是在開發中的終端(在生產中,也許是foreverjs )中使用node命令:

Linux / OS X:

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

視窗:

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

然后,在此服務器端腳本上,您必須觸發您感興趣的websockets事件。 (請注意初始化的順序: io應該在http服務器之后初始化)

例如,您可以使用io.emit(eventName, arguments)在全局范圍內emitio.emit(eventName, arguments)或者也可以emit其發送到一個namespace ,甚至可以emit它發送到在io connection事件上收到的單個socket上: socket.emit(eventName, arguments)

eventName應該是您的客戶端JS將偵聽的字符串

arguments可以是您想要的

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);
}

我認為您做錯了很多事,但我會盡力為您提供一些建議。

首先,我不以正確的方式啟動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();
}

確保div #welcome的CSS沒有

visibility: hidden;

由於僅將其顯示為一個塊是行不通的,因為它實際上仍然隱藏在CSS中。

如果它是隱藏的,則可以向Javascript添加另一行:

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

還要檢查是否設置了高度和寬度等。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM