[英]Where is the Socket.IO client-side .js file located?
I am trying to get socket.io (Node library) to work.我正在尝试让 socket.io(节点库)工作。
I have the server-side js working, and it is listening.我有服务器端 js 工作,它正在侦听。 The socket.io website states simply: socket.io 网站简单说明:
<script src="/socket.io/socket.io.js"></script>
<script>
var socket = io.connect('http://localhost');
socket.on('news', function (data) {
console.log(data);
socket.emit('my other event', { my: 'data' });
});
</script>
This is nice, however, what JS file am I importing!?!这很好,但是,我要导入什么 JS 文件!?!
I went into the node_modules directory, where I installed socket.io through npm, and inside socket.io/lib/
is socket.io.js
file.我走进node_modules目录,其中我安装socket.io通过NPM和内部socket.io/lib/
是socket.io.js
文件。 However, this is server-side (uses the phrase require()
, which errors on the client).但是,这是服务器端的(使用短语require()
,它在客户端上出错)。
I have spent an hour looking around and I can't get any client .js file to work.我花了一个小时环顾四周,但无法让任何客户端 .js 文件正常工作。
What am I missing?我错过了什么?
I managed to eventually answer this for myself.我最终设法为自己回答了这个问题。
The socket.io getting started page isn't clear on this, but I found that the server side of socket.io automatically hosts the .js file on starting node, in the directory specified in the documentation: socket.io 入门页面对此并不清楚,但我发现 socket.io 的服务器端自动将 .js 文件托管在起始节点上,在文档中指定的目录中:
"/socket.io/socket.io.js"
So you literally just point to this url regardless of your web app structure, and it works.因此,无论您的 Web 应用程序结构如何,您都只需指向此 url,它就可以工作。
I would suggest checking if your node_modules directory is at the top level of your app directory.我建议检查您的 node_modules 目录是否位于应用程序目录的顶层。 Also, I do believe you need to specify a port number;另外,我相信您需要指定一个端口号; you should write something like var socket = io.connect('http://localhost:1337');
你应该写类似var socket = io.connect('http://localhost:1337');
, where the port number is 1337
. ,其中端口号是1337
。
If you did npm install
then the client socket.io file is located at node_modules/socket.io-client/dist/socket.io.js如果您npm install
了npm install
那么客户端 socket.io 文件位于 node_modules/socket.io-client/dist/socket.io.js
Source: Socket get-started page来源: Socket 入门页面
The client is available in a few ways:客户端可以通过以下几种方式使用:
/socket.io/socket.io.js
由 socket.io 服务器在/socket.io/socket.io.js
socket.io-client
通过 webpack 作为模块socket.io-client
https://cdnjs.cloudflare.com/ajax/libs/socket.io/<version>/socket.io.js
通过官方 CDN https://cdnjs.cloudflare.com/ajax/libs/socket.io/<version>/socket.io.js
For the first one, the server can be configured in a couple of ways:对于第一个,可以通过两种方式配置服务器:
// standalone
var io = require('socket.io')(port);
// with existing server from e.g. http.createServer or app.listen
var io = require('socket.io')(server);
在这里您可以找到各种版本的 CDN。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.