Javascript 在Express 4和Express generator'中使用socket.io;s/bin/www
所以这里是交易:我正在尝试在一个express项目中使用socket.io。Express Js 4启动后,我更新了我的Express generator,现在应用程序的初始函数进入Javascript 在Express 4和Express generator'中使用socket.io;s/bin/www,javascript,node.js,express,socket.io,Javascript,Node.js,Express,Socket.io,所以这里是交易:我正在尝试在一个express项目中使用socket.io。Express Js 4启动后,我更新了我的Express generator,现在应用程序的初始函数进入/bin/www文件,包括那些变量(www文件内容:) (通过npm安装-g express generator和express myApp 话虽如此,让我们记住socket.io文档是如何要求我们启动它的: var app = require('express').createServer(); var io =
/bin/www
文件,包括那些变量(www文件内容:)
(通过npm安装-g express generator
和express myApp
话虽如此,让我们记住socket.io文档是如何要求我们启动它的:
var app = require('express').createServer();
var io = require('socket.io')(app);
好的,但我不能在app.js中这样做,就像推荐的那样。这应该在./bin/www中完成才能工作。在./bin/www中,我可以这样做才能让它工作:
var io = require('socket.io')(server)
好的,这是可行的,但是我不能在其他任何地方使用io变量,我真的不想把我的socket.io函数放在www
文件中
我想这只是基本语法,但我无法实现这一点,甚至不能在www文件上使用module.exports=server
或server.exports=server
或module.exports.io=app(io)
所以问题是:如何使用socket.io将这个/bin/www文件作为我的应用程序的起点?事实证明这确实是一些基本的sintax问题……我从 在./bin/www上,就在
var server=app.listen(…)
现在我创建../sockets/base.js文件并将这个小家伙放在其中:
module.exports = function (io) { // io stuff here... io.on('conection..... }
是的!现在它可以工作了…所以我想除了在/bin/www中启动socket.io之外,我真的没有别的选择了,因为我的http服务器就是从这里启动的。
目标是现在我可以通过require('fileHere')(io);
以下是如何将Socket.io添加到新生成的Express Generator应用程序:
socketapi.js
:const io = require( "socket.io" )();
const socketapi = {
io: io
};
// Add your socket.io logic here!
io.on( "connection", function( socket ) {
console.log( "A user connected" );
});
// end of socket.io logic
module.exports = socketapi;
/**
* Module dependencies.
*/
var app = require('../app');
var debug = require('debug')('socketexpress:server');
var http = require('http');
let socketapi = require("../socketapi"); // <== Add this line
/**
* Get port from environment and store in Express.
*/
var port = normalizePort(process.env.PORT || '3000');
app.set('port', port);
/**
* Create HTTP server.
*/
var server = http.createServer(app);
socketapi.io.attach(server); // <== Also add this line
(...)
bin/www
启动器。有两个步骤:需要Socket.io api并在创建HTTP服务器后立即将HTTP服务器连接到Socket.io实例:const io = require( "socket.io" )();
const socketapi = {
io: io
};
// Add your socket.io logic here!
io.on( "connection", function( socket ) {
console.log( "A user connected" );
});
// end of socket.io logic
module.exports = socketapi;
/**
* Module dependencies.
*/
var app = require('../app');
var debug = require('debug')('socketexpress:server');
var http = require('http');
let socketapi = require("../socketapi"); // <== Add this line
/**
* Get port from environment and store in Express.
*/
var port = normalizePort(process.env.PORT || '3000');
app.set('port', port);
/**
* Create HTTP server.
*/
var server = http.createServer(app);
socketapi.io.attach(server); // <== Also add this line
(...)
然后,在您的bin/www
启动器中,不要在自己的行中导入套接字api,只需在应用程序中导入它即可:
bin/www
var {app, socketapi} = require('../app'); // <== Import your app and socket api like this
(...)
var server = http.createServer(app);
socketapi.io.attach(server); // <== You still have to attach your HTTP server to your socket.io instance
/**
* Socket.io
*/
var socketApi = require('../socketApi');
var io = socketApi.io;
io.attach(server);
var{app,socketapi}=require('../app');//旧的“expressjs”,所有事情都发生在文件“app.js”中。因此,socket.io绑定到服务器也发生在该文件中。(顺便说一句,我们仍然可以用旧的方式来做,并删除bin/www)
现在有了新的expressjs,它需要在“bin/www”文件中发生
幸运的是,javascript/requirejs使传递对象变得很容易。正如Gabriel Hautclocq所指出的,socket.io仍然在“app.js”中“导入”,并通过属性连接到“app”对象
app.io = require('socket.io')();
通过在“bin/www”中将服务器连接到socket.io,使其处于活动状态
因为“app”对象在前面被传递到“bin/www”
这真的很简单
require('socket.io')().attach(server);
但是以“困难”的方式进行操作可以确保app.io
现在保存socke.io对象
现在,如果您在“routes/index.js”中也需要这个socket.io对象,只需使用相同的原理来传递该对象
首先在“app.js”中
然后在“routes/index.js”中
因此,“io”被注入到“index.js”中。初学者教程
以下是应用程序聊天链接的简短基础:
使用express生成
还有ejs引擎
可用于express generate中的每个.ejs文件标准路由
编辑文件bin\www并添加此app.io.attach(服务器);如下所示
...
/*
* Create HTTP server.
/*
var server = http.createServer(app);
/*
* attach socket.io
/*
app.io.attach(server);
/*
* Listen to provided port, on all network interfaces.
/*
...
在app.js中编辑
//connect socket.io
... var app = express();
// call socket.io to the app
app.io = require('socket.io')();
//view engine setup
app.set('views', path.join(_dirname, 'views'));
...
...
//start listen with socket.io
app.io.on('connection', function(socket){
console.log('a user connected');
// receive from client (index.ejs) with socket.on
socket.on('new message', function(msg){
console.log('new message: ' + msg);
// send to client (index.ejs) with app.io.emit
// here it reacts direct after receiving a message from the client
app.io.emit('chat message' , msg);
});
});
...
module.exports = app;
在index.ejs中编辑
var express = require('express');
var socketapi = require("./socketapi"); // <== Add this line
(...)
// You can now access socket.io through the socketapi.io object
(...)
module.exports = { app, socketapi }; // <== Export your app and re-export your socket API here
<head>
<title><%= title %></title>
<link rel='stylesheet' href='/stylesheets/style.css' />
<script src="/socket.io/socket.io.js"></script>
//include jquery
<script src="//code.jquery.com/jquery-1.11.3.min.js"></script>
<script>
var socket = io();
//define functions socket.emit sending to server (app.js) and socket.on receiving
// 'new message' is for the id of the socket and $('#new-message') is for the button
function sendFunction() {
socket.emit('new message', $('#new-message').val());
$('#new-message').val('');
}
// 'chat message' is for the id of the socket and $('#new-area') is for the text area
socket.on('chat message', function(msg){
$('#messages-area').append($('<li>').text(msg));
});
</script>
</head>
<body>
<h1><%= title %></h1>
<h3>Welcome to <%= title %></h3>
<ul id="messages-area"></ul>
<form id="form" onsubmit="return false;">
<input id="new-message" type="text" /><button onclick="sendFunction()">Send</button>
</form>
</body>
var socket_io = require('socket.io');
var io = socket_io();
var socketApi = {};
socketApi.io = io;
io.on('connection', function(socket){
console.log('A user connected');
});
socketApi.sendNotification = function() {
io.sockets.emit('hello', {msg: 'Hello World!'});
}
module.exports = socketApi;
// Nothing here
//包含jquery
var socket=io();
//定义函数socket.emit发送到服务器(app.js)和socket.on接收
//“new message”表示套接字的id,$(“#new message”)表示按钮
函数sendFunction(){
emit('newmessage',$('#newmessage').val());
$(“#新消息”).val(“”);
}
//“chat message”表示套接字的id,$(“#new area”)表示文本区域
socket.on('chat message',函数(msg){
$(“#消息区”).append($(“”).text(msg));
});
欢迎来到
发送
玩得开心:)
多亏了的最新回复:
在www文件中,由于使用Socket.io进行了更新,代码应显示如下现在开始收听。
/**
* Create HTTP server.
*/
var server = http.createServer(app);
/**
* Listen on provided port, on all network interfaces.
*/
server.listen(port);
server.on('error', onError);
server.on('listening', onListening);
/**
* Socket.io
*/
var io = app.io;
io.listen(server);`
此外,要使该连接正常工作,还需要实现客户端API。这不是特定于Express的,但如果没有它,connect调用将无法工作。API包含在
/node_modules/socket.io-client/socket.io.js.
在前端包含此文件,并使用以下内容进行测试:
var socket = io.connect('http://localhost:3000');
var sockIO = app.sockIO;
sockIO.listen(server);
以前的一些答案不起作用,而另一些答案过于复杂。请尝试以下解决方案
安装服务器端和客户端socket.io节点模块:
npm install --save socket.io socket.io-client
服务器端
在服务器定义之后向bin/www添加以下代码,var server=http.createServer(app)代码>:
客户端
如果使用webpack,请将以下代码添加到webpack entry.js文件中:
完成了。访问您的站点并查看浏览器的js开发者控制台。阅读所有评论后,我使用Socket.io服务器版本提出了以下建议:1.5.0
我遇到的问题:
var sockIO=require('socket.io')应该是var sockIO=require('socket.io')()。(贷记:)
sockIO.attach应该是sockIO。收听(归功于:)
步骤
var express = require('express');
var socketapi = require("./socketapi"); // <== Add this line
(...)
// You can now access socket.io through the socketapi.io object
(...)
module.exports = { app, socketapi }; // <== Export your app and re-export your socket API here
<head>
<title><%= title %></title>
<link rel='stylesheet' href='/stylesheets/style.css' />
<script src="/socket.io/socket.io.js"></script>
//include jquery
<script src="//code.jquery.com/jquery-1.11.3.min.js"></script>
<script>
var socket = io();
//define functions socket.emit sending to server (app.js) and socket.on receiving
// 'new message' is for the id of the socket and $('#new-message') is for the button
function sendFunction() {
socket.emit('new message', $('#new-message').val());
$('#new-message').val('');
}
// 'chat message' is for the id of the socket and $('#new-area') is for the text area
socket.on('chat message', function(msg){
$('#messages-area').append($('<li>').text(msg));
});
</script>
</head>
<body>
<h1><%= title %></h1>
<h3>Welcome to <%= title %></h3>
<ul id="messages-area"></ul>
<form id="form" onsubmit="return false;">
<input id="new-message" type="text" /><button onclick="sendFunction()">Send</button>
</form>
</body>
var socket_io = require('socket.io');
var io = socket_io();
var socketApi = {};
socketApi.io = io;
io.on('connection', function(socket){
console.log('A user connected');
});
socketApi.sendNotification = function() {
io.sockets.emit('hello', {msg: 'Hello World!'});
}
module.exports = socketApi;
// Nothing here
使用以下命令安装Socket.io:
npm install --save socket.io
将以下内容添加到app.js:
var sockIO = require('socket.io')();
app.sockIO = sockIO;
在bin/www中,在var server=http.c之后
sockIO.on('connection', function(socket){
console.log('A client connection occurred!');
});
/**
* Socket.io
*/
var socketApi = require('../socketApi');
var io = socketApi.io;
io.attach(server);
var socket_io = require('socket.io');
var io = socket_io();
var socketApi = {};
socketApi.io = io;
io.on('connection', function(socket){
console.log('A user connected');
});
socketApi.sendNotification = function() {
io.sockets.emit('hello', {msg: 'Hello World!'});
}
module.exports = socketApi;
// Nothing here