首页 文章

使用socket.io从另一台服务器接收客户端变量

提问于
浏览
0

概述

我正在与两个实体合作:(i)IRC webapp和(ii)IRC机器人 . 有一个机器人变量 botVariable ,我试图使用 socket.io 来做这个并且失败了 . To me, what makes this problem interesting is that I'm trying to pass a value not from the IRC webapp server to the webapp client, but from the bot server to the webapp client. 这是我第一次使用socket.io . bot和irc webapp都托管在(不同的)heroku url上 .

Bot代码(服务器端)

对于机器人,我有以下代码:

var botVariable = "bot string"; //botVariable is global.

var io = require('socket.io')(HTTPS);
io.on('connection', function(botVariable) {
    //When client connects for the first time, send him the value immediately
    socket.emit('new_value', botVariable);
    console.log(botVariable);
});

console.log("End of bot file.");

IRC代码(客户端)

对于IRC客户端代码,我有以下内容:

<head>
<script src="https://bot.herokuapp.com/socket.io/socket.io.js"></script>
</head>

<h2 id="bv" align="center"></h2> // where I eventually want to show botVariable

<script>
var socket = io.connect("http://bot.herokuapp.com/"); //this is where I host the bot

socket.on('new_value', function(botVariable) {
console.log(botVariable);
cBotVariable = botVariable; //I'm trying to make cBotVariable a global variable I can refer to on the client side
});

document.getElementById("bv").innerHTML = cBotVariable;
</script>

结果/错误

当我加载网站时, botVariable 无法显示 . 我在控制台中收到以下错误 .

> GET http://bot.herokuapp.com/socket.io/socket.io.js 
(index):78 

> Uncaught ReferenceError: io is not defined

当我去bot.herokuapp.com/socket.io/socket.io.js时,它说 Could not find path: /socket.io/socket.io.js .

我的印象是你不需要提供这个文件,但服务器会以某种方式动态创建它 . 我想情况并非如此?

1 回答

  • 1

    尝试安装socket.io

    npm install socket.io
    

    并包括:

    <script src="PATH_TO_NODE_MODULES/socket.io/node_modules/socket.io-client/dist/socket.io.js"></script>
    

    或使用CDN:

    <script src="https://cdn.socket.io/socket.io-1.2.1.js"></script>
    

相关问题