使用Socket.io连接到特定的服务器IP [英] Connecting to a specific Server Ip with Socket.io

查看:854
本文介绍了使用Socket.io连接到特定的服务器IP的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我必须为移动设备构建一个跨平台的Web应用程序,因此我正在使用html,css和js(然后它将通过phonegap或cordova)进行开发.

I have to build a crossplatform web app for mobile devices, so I'm developing it with html, css and js (then it will pass through phonegap or cordova).

我的问题正在使用socket.io,我的问题是:

My problem is working with socket.io, and my questions are:

1)我可以连接到客户端上的特定IP吗?

1) Can I connect to a specific ip on the 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>

我需要这个,但这不起作用:

I need this, but this doesn't work:

<script src="my-app/folder/js/socket.io/socket.io.js"></script>
<script>
  var socket = io.connect('http://my.server.ip:port');
  socket.on('news', function (data) {
    console.log(data);
    socket.emit('my other event', { my: 'data' });
  });
</script>

2)在服务器端,如何创建一个服务器来侦听其IP上的连接和消息?

2) On the server side, how can I create a server that listen to connections and messages on its IP?

var io = require('socket.io').listen(80, my.server.ip);

通过这种方式,应用程序的用户将连接到托管聊天服务的服务器Ip.

In this way, the application's users will connect to my server Ip in which I host the chat service.

我想我没有考虑socket.io的正确逻辑.

I suppose that I'm not in thinking in the right logic of socket.io .

推荐答案

部署应用程序时,您将不会连接到本地主机,并且设备将连接到服务器主机名或IP地址.

You will not be connecting to localhost when you deploy the application and the devices will be connecting to the server hostname or IP address.

服务器上的以下代码将在指定端口上与该服务器关联的IP地址上运行socket.io,前提是该IP地址上的服务器可访问

The following code on your server will run socket.io on an IP address associated with the server on the specified port provided that the server is accessible on that IP address

var io = require('socket.io');
var server = http.createServer();
server.listen(port, ipAddress);
var socket = io.listen(server);

下面的代码在客户端应该可以正常工作

The following code should work fine on the client side

var socket = new io.Socket();
socket.connect('http://' + ipAddress + ':' + port);

请确保您能够从客户端设备通过网络连接到IP地址,以使其正常工作.

Make sure you are able to connect to the IP address across the network from the client device for this to work.

这篇关于使用Socket.io连接到特定的服务器IP的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆