[英]node.js Socketio and dynamic content
I'm trying to make it so that when nodejs triggers something in an irc chat that a html page (Running on *:3000) will execute some JavaScript. 我试图做到这一点,以便当nodejs在irc聊天中触发某些内容时,html页面(在*:3000上运行)将执行一些JavaScript。 When I try to achieve this, it runs through the code but doesn't execute showDiv(); 当我尝试实现此目标时,它将运行代码,但不执行showDiv();。
I'm running this in chrome with localhost:3000 open. 我在localhost:3000打开的chrome中运行它。
Why won't the div with the id "welcome" change to visible when I type !follow in the IRC which is being picked up. 当我在正在拾取的IRC中键入!follow时,为什么id为“ welcome”的div不会变为可见。
Full code: 完整代码:
Index.html: 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: 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();
});
}
});
I think you are confusing between NodeJS server-side script, and JS client-side one. 我认为您在NodeJS服务器端脚本和JS客户端脚本之间感到困惑。
You cannot directly call "example.js", which is your server-side script, directly from client-side. 您不能直接从客户端直接调用服务器端脚本“ example.js”。
You have to launch it as a NodeJS http server, basically with the node
command in your terminal in development (in production, maybe with foreverjs ) : 您必须将其作为NodeJS http服务器启动,基本上是在开发中的终端(在生产中,也许是foreverjs )中使用node
命令:
Linux / OS X: Linux / OS X:
cd /path/to/your/project/folder
node example.js
Windows: 视窗:
dir \path\to\your\project\folder
node example.js
Then, on this server-side script, you have to trigger the websockets events you are interested by. 然后,在此服务器端脚本上,您必须触发您感兴趣的websockets事件。 (Pay attention to the order of initialisation: io
should be initialised AFTER the http server) (请注意初始化的顺序: io
应该在http服务器之后初始化)
For instance, you can emit
it globally with io.emit(eventName, arguments)
Or you can also emit
it to a namespace
, or even emit
it to a single socket
, received on io
connection
event: socket.emit(eventName, arguments)
例如,您可以使用io.emit(eventName, arguments)
在全局范围内emit
它io.emit(eventName, arguments)
或者也可以emit
其发送到一个namespace
,甚至可以emit
它发送到在io
connection
事件上收到的单个socket
上: socket.emit(eventName, arguments)
eventName
should be a string that your client-side JS will listen for eventName
应该是您的客户端JS将侦听的字符串
arguments
could be whatever you want arguments
可以是您想要的
The documentation overview of socket.io is full of very good examples. socket.io的文档概述中包含许多非常好的示例。
Example: 例:
Server-side 服务器端
// 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);
And remember that on server-side, you cannot call client-side functions! 请记住,在服务器端,您不能调用客户端函数!
Then, on the client side (which should be another file than example.js), you only have to listen for this given event: 然后,在客户端(应该是example.js之外的另一个文件),您只需要侦听此给定事件:
Client-side 客户端
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);
}
You are doing lot of thing wrong I think but I will try to help you with some advice. 我认为您做错了很多事,但我会尽力为您提供一些建议。
First you don't start socket.io the right way I think. 首先,我不以正确的方式启动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);
Second you don't emit socket.io event on server For me you have to do this in client listener 其次,您不会在服务器上发出socket.io事件。对于我来说,您必须在客户端侦听器中执行此操作
// This code is on server
// To send an event from server to client you have to use io
io.emit('follow');
Third, you don't receive event on the client 第三,您不会在客户端上收到事件
// 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();
}
Make sure that the CSS for the div #welcome
doesn't have 确保div #welcome
的CSS没有
visibility: hidden;
As simply displaying it as a block will not work as it is effectively still hidden in the CSS. 由于仅将其显示为一个块是行不通的,因为它实际上仍然隐藏在CSS中。
If it is hidden then you can add another line to your Javascript: 如果它是隐藏的,则可以向Javascript添加另一行:
function showDiv() {
document.getElementById('welcome').style.display = "block";
document.getElementById('welcome').style.visibility = "visible";
}
Also check that the height and width are set etc. 还要检查是否设置了高度和宽度等。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.