【发布时间】:2015-12-10 20:23:22
【问题描述】:
我正在尝试设置一个 WebSocket 来运行一个简单的聊天应用程序。
我有一个用户使用在服务器 A 上运行的 PHP 应用程序。另一方面,我有服务器 B,它使用 node.js 和 Socket.io 运行 WebSocket。
我按照Socket.io 教程编写了一个小型聊天应用程序。但似乎我需要在我的客户端脚本中包含socket.io.js 文件来启动用户和Websocket 之间的连接。但是,我似乎不知道从哪里获取 socket.io.js 文件。
在哪里可以找到socket.io.js?
不确定我的代码在这种情况下是否重要,但如果需要的话。
这是我的 socket.js 文件“Websocket”服务器
var env = require('./config');
var app = require('express')();
var server = require('http').Server(app);
var io = require('socket.io')(server);
server.listen(env.socket.port, env.socket.host, function () {
var host = server.address().address;
var port = server.address().port;
console.log('Example app listening at http://%s:%s', host, port);
});
app.get('/', function (req, res) {
res.send('Landed!');
});
io.on('connection', function (socket) {
socket.emit('news', { hello: 'world' });
socket.on('my other event', function (data) {
console.log(data);
});
});
这是我的客户端代码
<!doctype html>
<html lang="en-US">
<head>
<title>Socket.IO chat</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; }
</style>
<script src="/socket.io.js"></script>
<script type="text/javascript" src="/js/jquery-2.1.0.min.js"></script>
<script>
var socket = io();
$('form').submit(function(){
socket.emit('chat message', $('#m').val());
$('#m').val('');
return false;
});
socket.on('chat message', function(msg){
$('#messages').append($('<li>').text(msg));
});
</script>
</head>
<body>
<ul id="messages"></ul>
<form action="">
<input id="m" autocomplete="off" /><button>Send</button>
</form>
</body>
</html>
【问题讨论】:
-
不知道为什么要投反对票!我将感谢选民的解释。
-
本教程显示脚本位于
/socket.io/socket.io.js,假设页面是从与套接字服务器相同的服务器呈现的。这应该很快转换为http://mysocketserver.com/socket.io/socket.io.js您也可以直接从站点或cdn 下载socket.io 客户端。 -
@KevinB 感谢您的帮助。我包含了该文件,但我仍然收到此错误
ReferenceError: io is not defined -
如果您查看控制台,您还应该看到未找到 socket.io.js,这比 js 错误重要得多。修复 js 错误的唯一方法是正确引用该文件。
-
我相信这已经被讨论(回答)[这里][1]。 [1]:stackoverflow.com/questions/17757728/…
标签: javascript node.js sockets websocket socket.io