Jun*_*ior 3 javascript sockets websocket node.js socket.io
我正在尝试设置一个 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);
});
});
Run Code Online (Sandbox Code Playgroud)
这是我的客户端代码
<!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>
Run Code Online (Sandbox Code Playgroud)
您的 HTML 不正确。这是您需要的线路:
<script src="/socket.io/socket.io.js"></script>
Run Code Online (Sandbox Code Playgroud)
这很令人困惑,因为socket.io.js磁盘上没有明显的文件。它由您的 Express Web 应用程序中的 socket.io 自动提供,但路径/socket.io/socket.io.js是完全虚拟的,不会直接映射到文件系统上的目录或文件。
这是socket.io 服务器从 socket.io-client npm 模块加载 socket.io.js 文件源代码的源代码,然后在/socket.io/socket.io.js请求URL 时将其发送到浏览器。
如果您只想获取文件并将其粘贴到您的 PHP 服务器中,它位于官方 socket.io-client github 存储库中
| 归档时间: |
|
| 查看次数: |
10308 次 |
| 最近记录: |