简体   繁体   English

你如何在同一个端口上运行express和socket.io

[英]How do you run express and socket.io on the same port

its always annoying i have to always run listen to a new port in my app.js meaning eg i can access my website with localhost:3000 and localhost:4000 and socket.io on my site works only using localhost:4000. 它总是令人讨厌,我必须总是在我的app.js中听一个新的端口,这意味着我可以访问我的网站localhost:3000和localhost:4000和我的网站上的socket.io只能使用localhost:4000。 I just pushed it to heroku and realised i cant even change the port on heroku 我只是把它推到了heroku并意识到我甚至无法更改heroku上的端口

this is what i have 这就是我所拥有的

app.js: app.js:

var express = require("express");
var io = require('socket.io')
var port = 3000;

var app = express()
  , server = require('http').createServer(app)
  , io = io.listen(server);

server.listen(3000);

module.exports = io;

client.js: client.js:

var socket = io('http://localhost/');

I'm able to do what you want with: 我能够做你想做的事:

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

//setup stuff

server.listen(3000)

The simplest version of express 4 + socket.io 1.0 (which I use myself) is this: 最简单的express 4 + socket.io 1.0版本(我自己使用)是这样的:

var express = require('express');
var app = express();
var server = app.listen(3000, function() {
    console.log("server started on port 3000");
});

var io = require('socket.io').listen(server);

I don't honestly know why your version doesn't work, but have advised several people to follow this sequence (which I got from the documentation) and it has worked for myself and for them. 我不知道为什么你的版本不起作用,但已经建议几个人遵循这个顺序(我从文档中得到)并且它对我自己和他们都有效。 It probably has to do with io getting plugged into express 4 appropriately and not using the general http module, but express instead. 它可能与io适当地插入Express 4并且不使用通用http模块有关,但是express

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

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