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

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

主站蜘蛛池模板: 双鸭山市| 晋江市| 龙海市| 麦盖提县| 芒康县| 广南县| 灌南县| 隆回县| 安吉县| 连平县| 偃师市| 泸西县| 龙陵县| 区。| 朝阳县| 内丘县| 泽州县| 三原县| 吉首市| 慈利县| 开化县| 明光市| 无锡市| 平山县| 堆龙德庆县| 昌邑市| 分宜县| 新巴尔虎右旗| 依兰县| 阿克苏市| 石棉县| 天长市| 自贡市| 邵武市| 吉隆县| 呼和浩特市| 广南县| 家居| 潮安县| 南和县| 九寨沟县|