官术网_书友最值得收藏!

  • Socket.IO Cookbook
  • Tyson Cadenhead
  • 527字
  • 2021-07-09 21:49:09

Creating an Express server with Socket.IO

Express is probably the most widely used Node application framework available. Numerous MVC frameworks are written based on Express, but it can also be used on its own. Express is simple, flexible, and unopinionated, which makes it a pleasure to work with.

Socket.IO can be used based on the Express server just as easily as it can run on a standard Node HTTP server. In this section, we will fire the Express server and ensure that it can talk to the client side via Socket.IO.

Getting ready

The Express framework runs on Node, so you will need to have Node installed on your machine. Refer to the previous recipe for instructions on how to install Node and Socket.IO.

In addition to Node and Socket.IO, you will also need to install the Express npm package. Express can be installed by entering npm install express --save on your terminal.

How to do it…

Follow these steps to create an Express server using Socket.IO:

  1. You will need to create a new server-side JavaScript file called server.js. It will contain all of your server instantiation and handle your Socket.IO messaging. The server.js file will look similar to the following code:
    var express = require('express'),
        app = express(),
        http = require('http'),
        socketIO = require('socket.io'),
        server, io;
    
    app.get('/', function (req, res) {
    res.sendFile(__dirname + '/index.html');
    });
    
    server = http.Server(app);
    server.listen(5000);
    
    io = socketIO(server);
    
    io.on('connection', function (socket) {
      socket.emit('greeting-from-server', {
          greeting: 'Hello Client'
      });
      socket.on('greeting-from-client', function (message) {
        console.log(message);
      });
    });
  2. The server.js file will serve a static HTML file called index when the user navigates to the root directory of the server. The HTML file will handle the client-side Socket.IO messaging. It will look similar to the following code:
    <!DOCTYPE html>
    <html>
    <head>
    </head>
    <body>
    <script src="/socket.io/socket.io.js"></script>
    <script>
                var socket = io('http://localhost:5000');
                socket.on('greeting-from-server', function (message) {
                    document.body.appendChild(
                        document.createTextNode(message.greeting)
                    );
                    socket.emit('greeting-from-client', {
                        greeting: 'Hello Server'
                    });
                });
    </script>
    </body>
    </html>
  3. Once both of your files are created, you can start your server by entering node server on your terminal.
  4. After the server starts, you should be able to navigate to http://localhost:5000 and see a message that says Hello Client:
    How to do it…
  5. There should be a message that says 'Hello Server' on your terminal:
    How to do it…

Awesome! Now you've got Socket.IO running on Express.

How it works…

Express is a collection of HTTP utilities and middleware that make it easier to use Node as a web server. Although Express provides a robust API that isn't available out of the box from the built-in Node HTTP module, using Express with Socket.IO is still very similar.

We created a new Express server with var app = express(). We passed this to the http.Server() method. By passing our Express app as the first argument to the HTTP server, we told Node that we wanted to use Express as our handler for HTTP requests.

Next, we passed the HTTP server directly to the SocketIO method exactly as we would have if we were using a nonExpress HTTP server. Socket.IO took the server instance to listen for new socket connections on it. The new connections came from the client side when we navigated to the page in our browser.

See also

Creating a Node HTTP server with Socket.IO.

主站蜘蛛池模板: 北碚区| 綦江县| 普格县| 绥化市| 大港区| 晴隆县| 浦东新区| 扎鲁特旗| 永胜县| 修武县| 阿坝县| 专栏| 时尚| 渝中区| 略阳县| 阿城市| 喜德县| 彰化县| 兴城市| 上杭县| 长海县| 庆云县| 孝感市| 龙山县| 大城县| 七台河市| 江山市| 布拖县| 南靖县| 保德县| 班戈县| 刚察县| 绥滨县| 济源市| 阿瓦提县| 连云港市| 霍州市| 石阡县| 天柱县| 广德县| 绵竹市|