IT박스

Express 4 및 Express 생성기의 / bin / www에서 socket.io 사용

itboxs 2020. 9. 20. 09:12
반응형

Express 4 및 Express 생성기의 / bin / www에서 socket.io 사용


그래서 여기에 거래가 있습니다 : 나는 익스프레스 프로젝트에서 socket.io를 사용하려고합니다. Express Js 4가 출시 된 후 Express 생성기를 업데이트했으며 이제 ./bin/www해당 변수를 포함한 앱 초기 기능이 파일에 저장됩니다 (www 파일 콘텐츠 : http://jsfiddle.net/avMa5/ ).

var server = app.listen(app.get('port'), function() {..}

(확인 npm install -g express-generatorexpress 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 var를 사용할 수 없으며 실제로 socket.io 함수를 www파일 에 넣고 싶지 않습니다 .

나는 이것이 기본적인 구문이라고 생각하지만 www 파일을 사용 module.exports = server하거나 사용 server.exports = server하지도 않고 작동하도록 할 수 없습니다.module.exports.io = app(io)

그래서 질문은 :이 / bin / www 파일을 내 앱의 시작점으로 갖는 socket.io를 어떻게 사용할 수 있습니까?


app.js에서 socket.io를 사용할 수 있도록하는 솔루션이 있습니다.

app.js :

var express      = require( "express"   );
var socket_io    = require( "socket.io" );

// Express
var app          = express();

// Socket.io
var io           = socket_io();
app.io           = io;

(...)

// socket.io events
io.on( "connection", function( socket )
{
    console.log( "A user connected" );
});

module.exports = app;

// Or a shorter version of previous lines:
//
//    var app = require( "express"   )();
//    var io  = app.io = require( "socket.io" )();
//    io.on( "connection", function( socket ) {
//        console.log( "A user connected" );
//    });
//    module.exports = app;

bin / www :

(...)

/**
 * Create HTTP server.
 */

var server = http.createServer( app );


/**
 * Socket.io
 */

var io     = app.io
io.attach( server );

(...)

이렇게하면 app.js에서 io 변수에 액세스 할 수 있으며 module.exports를 매개 변수로 io를 허용하는 함수로 정의하여 경로에서 사용할 수 있도록 할 수도 있습니다.

index.js

module.exports = function(io) {
    var app = require('express');
    var router = app.Router();

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

    return router;
}

그런 다음 설정 후 io를 모듈에 전달합니다.

app.js

// Socket.io
var io = socket_io();
app.io = io;

var routes = require('./routes/index')(io);

시작하는 약간 다른 접근 방식으로 socket.io모든 관련 코드를 한곳에 그룹화합니다.

bin / www

/**
 * Socket.io
 */
var socketApi = require('../socketApi');
var io = socketApi.io;
io.attach(server);

socketApi.js

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;

app.js

// Nothing here

이런 식으로 socket.io하나의 모듈에있는 모든 관련 코드와 그것의 기능을 응용 프로그램의 어느 곳에서나 호출 할 수 있습니다.


그것은 정말로 기본적인 신택스 문제였습니다 .... 이 socket.io 채팅 튜토리얼에서이 줄을 얻었습니다 ...

./bin/www에서 var server = app.listen(.....)

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

이제 ../sockets/base.js 파일을 만들고 그 안에이 작은 친구를 넣습니다.

module.exports = function (io) { // io stuff here... io.on('conection..... }

네! 이제 작동합니다 ... 그래서 내 http 서버가 시작된 곳이기 때문에 / bin / www 내부에서 socket.io를 시작하는 것 외에는 옵션이 없었습니다. 목표는 이제 다른 파일에 소켓 기능을 구축하여 모듈화를 유지하는 것입니다.require('fileHere')(io);

<3


오래된 "expressjs", 모든 것이 "app.js"파일에서 일어나고 있습니다. 따라서 서버에 대한 socket.io 바인딩도 해당 파일에서 발생합니다. (BTW, 여전히 예전 방식으로 할 수 있으며 bin / www를 제거하십시오)

이제 새로운 expressjs에서는 "bin / www"파일에서 발생해야합니다.

다행히 javascript / requirejs를 사용하면 객체를 쉽게 전달할 수 있습니다. Gabriel Hautclocq가 지적했듯이 socket.io는 여전히 "app.js"에서 "가져 오기"되고 속성을 통해 "app"객체에 연결됩니다.

app.io = require('socket.io')();

socket.io는 "bin / www"에있는 서버에 연결하여 활성화됩니다.

app.io.attach(server); 

"app"객체는 이전에 "bin / www"로 전달되기 때문입니다.

app = require("../app");

정말 간단합니다.

require('socket.io')().attach(server);

그러나 "어려운"방식으로 수행하면 app.io이제 socke.io 개체가 유지됩니다.

예를 들어 "routes / index.js"에서도이 socket.io 객체가 필요한 경우 동일한 원칙을 사용하여 해당 객체를 전달합니다.

먼저 "app.js"에서

app.use('/', require('./routes/index')(app.io));

그런 다음 "routes / index.js"에서

module.exports = function(io){
    //now you can use io.emit() in this file

    var router = express.Router();



    return router;
 }

그래서 "io"는 "index.js"에 주입됩니다.


Update to Gabriel Hautclocq's response:

In www file, the code should appear as the following due to updates with Socket.io. Attach is now Listen.

/**
 * 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);`

Additionally getting that connection to work requires implementing the client side API as well. This isn't Express specific but without it the connect call won't work. The API is included in

/node_modules/socket.io-client/socket.io.js. 

Include this file on the front end and test with the following:

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

After reading through all of the comments, I came up with the following using Socket.io Server Version: 1.5.0

Issues that I ran into:

  1. var sockIO = require('socket.io') should be var sockIO = require('socket.io')(). (Credit to: Zhe Hu)

  2. sockIO.attach should be sockIO.listen (Credit to: rickrizzo)

Steps

  1. Install Socket.io with the following command:

    npm install --save socket.io
    
  2. Add the following to app.js:

    var sockIO = require('socket.io')();
    app.sockIO = sockIO;
    
  3. In bin/www, after var server = http.createServer(app), add the following:

    var sockIO = app.sockIO;
    sockIO.listen(server);
    
  4. To test functionality, in app.js, you can add the line:

    sockIO.on('connection', function(socket){
        console.log('A client connection occurred!');
    });
    

A tutorial for beginners from Cedric Pabst
here are the short basics form the link for an app chat:

using express-generate and the ejs engine usable in every .ejs file standard routing in express-generate

edit the file bin\www and add this app.io.attach(server); like this

...
/*
 * Create HTTP server.
/*  
var server = http.createServer(app);
/*
 * attach socket.io
/*  
app.io.attach(server); 
/*
 * Listen to provided port, on all network interfaces.
/*  
...

edit in 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;

edit in index.ejs

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

Have fun :) and thanks many to Cedric Pabst


Some previous answers are not working and others are overly complicated. Try the following solution instead...

Install server-side and client-side socket.io node modules:

npm install --save socket.io socket.io-client

Server-side

Add the following code to bin/www after the server definition, var server = http.createServer(app);:

/**
 * Socket.io
 */

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

io.on("connection", function(socket){
  console.log("SOCKET SERVER CONNECTION");
  socket.emit('news', { hello: 'world' });
});

Client-side

If using webpack, add the following code to your webpack entry.js file:

var socket = require('socket.io-client')();
socket.on('connect', function(){
  console.log("SOCKET CLIENT CONNECT")
});

socket.on('news', function(data){
  console.log("SOCKET CLIENT NEWS", data)
});

Done. Visit your site and check the browser's js developer console.

참고URL : https://stackoverflow.com/questions/24609991/using-socket-io-in-express-4-and-express-generators-bin-www

반응형