简体   繁体   English

卡在socket.io上

[英]Stuck on socket.io

So, I got node and downloaded the files, so I now have socket.io.js. 因此,我得到了节点并下载了文件,所以现在有了socket.io.js。

  1. How do I use it in my project? 如何在项目中使用它? Just like a normal JavaScript file? 就像普通的JavaScript文件一样?
  2. What kind of address am I supposed to enter when I try to connect, I'm editing locally (localhost), but what about when I move it to my server? 尝试连接时,我应该在本地编辑(本地主机),应该输入哪种地址,但是当我将其移至服务器时该怎么办?

I think - as long as it's not cross domain - you don't even have to pass the host name. 我认为-只要它不是跨域的-您甚至不必传递主机名。
So calling the connect() method without any arguments should work. 因此,调用不带任何参数的connect()方法应该可以工作。

see https://stackoverflow.com/a/15948558/1468708 参见https://stackoverflow.com/a/15948558/1468708

Answer to the first question: 回答第一个问题:

Did you use npm, node.js package manager ? 您是否使用过npm,node.js软件包管理器 In case you didn't, I would highly recommend it. 如果您没有,我强烈建议您。 When using npm you don't need to manually copy individual files to your project. 使用npm时,您无需手动将单个文件复制到项目中。

How to install npm depends on you operating system. 如何安装npm取决于您的操作系统。

After installation of npm you can run following command in you project folder to install socket.io package . 安装npm后,可以在项目文件夹中运行以下命令来安装socket.io软件包

npm install socket.io

On the socket.io npm package page is brief get started code snippet that got me started with it on server: socket.io npm软件包页面上,有简短的入门代码片段,使我在服务器上开始使用它:

var server = require('http').Server();
var io = require('socket.io')(server);

io.on('connection', function(socket){
  socket.on('event', function(data){});
  socket.on('disconnect', function(){});
});

server.listen(3000);

Source from socket.io package. 源于socket.io包。

Now your server socket is at location: 现在您的服务器套接字在以下位置:

http://localhost:3000

On client side: 在客户端:

<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>

Source from socket.io home page. 来源来自socket.io主页。

Answer to the second question: 回答第二个问题:

What kind of address am I supposed to enter when I try to connect, I'm editing locally (localhost), but what about when I move it to my server? 尝试连接时,我应该在本地编辑(本地主机),应该输入哪种地址,但是当我将其移至服务器时该怎么办?

You could on client side use for host and port following url: 您可以在客户端将以下网址用于主机和端口:

// You might need to add the port of socket connection to the url. 
// :3000 in this case
var socket = io.connect(location.host); 

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM