gpt4 book ai didi

javascript - Node.js Socketio 和动态内容

转载 作者:太空宇宙 更新时间:2023-11-04 02:25:43 24 4
gpt4 key购买 nike

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

我在 chrome 中运行此程序,并打开 localhost:3000。

当我在正在拾取的 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>

示例.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 服务器启动,基本上使用开发中终端中的 node 命令(在生产中,可能使用 foreverjs ):

Linux/OS X:

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

Windows:

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

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

例如,您可以使用 io.emit(eventName,arguments) 在全局范围内发出或者,您也可以将其发射命名空间,甚至发射到单个套接字,在io connection事件上接收:socket.emit(eventName, 参数)

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

参数可以是任何你想要的

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

关于javascript - Node.js Socketio 和动态内容,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30620972/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com