无法使用express和ejs使用socket.io

时间:2017-11-01 11:13:41

标签: express socket.io ejs

我是node.js,express和ejs的新手。我试图添加socket.io通信,但它不起作用。

index.ejs在浏览器中很好地显示,但日志消息未显示在服务器

// server side
var express = require('express');
var app = express();
var server = require('http').createServer(app);
var ejs = require('ejs');

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

// view engine
app.set('view engine', 'ejs');

// routing
app.get('/', function(req, res) {
  res.render('pages/index.ejs');
});

io.on('connection', function(socket){
  console.log('user connected');
});

app.use(function(req, res, next){
    res.setHeader('Content-Type', 'text/plain');
    res.status(404).send('Page not found !')
});

app.listen(8080);

// index.ejs

<!DOCTYPE html>
<html>
    <head>
        <meta charset="utf-8" />
        <title>Socket.io</title>
    </head>

    <body>
        <h1>Communication avec socket.io !</h1>

        <script src="/socket.io/socket.io.js"></script>
        <script>
            var socket = io();
        </script>
    </body>
</html>

2 个答案:

答案 0 :(得分:1)

让http服务器侦听端口8080.将app.listen(8080);替换为server.listen(8080);。然后,您可以看到日志消息'user connected'

答案 1 :(得分:0)

  • 您的代码如下所示

在&#34; /socket.io/socket.io.js"中调用index.ejs;错误地

enter image description here

更改了代码

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

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


app.set('view engine', 'ejs');

app.get('/', function(req, res) {
   res.render('../index.ejs');
});

io.on('connection', function(socket){
  console.log('user connected');
});

app.use(function(req, res, next){
    res.setHeader('Content-Type', 'text/plain');
    res.status(404).send('Page not found !')
});

server.listen(8080)

你将代码chagnged app.listen(8080)改为server.listen(8080)

enter image description here

正确的呼叫,然后是服务器端终端上的console.log

另外,套接字也可以使用命名空间

<强> app.js

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

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


app.get('/', function(req, res) {
  res.sendFile(__dirname + '/index.html');
});


// connection on namespace /chat
var chat = io.of('/chat').on('connection', function(socket) {

  socket.on('chat message', function(data){
    console.log('message from client: ', data);

    var name = socket.name = data.name;
    var room = socket.room = data.room;

    // join on room
    socket.join(room);
    // Sends a message to the client that is joined in the room
    chat.to(room).emit('chat message', data.msg);
  });
});

server.listen(3000, function() {
  console.log('Socket IO server listening on port 3000');
});

<强> index.html

<!DOCTYPE html>
<html>
<head>
  <meta charset="utf-8">
  <title>Socket.io Chat Example</title>
  <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">
</head>
<body>
  <div class="container">
    <h3>Socket.io Chat Example</h3>
    <!-- <form class="form-inline"> -->
    <form class="form-horizontal">
      <div class="form-group">
        <label for="name" class="col-sm-2 control-label">Name</label>
        <div class="col-sm-10">
          <input type="text" class="form-control" id="name" placeholder="Name">
        </div>
      </div>
      <div class="form-group">
        <label for="room" class="col-sm-2 control-label">Room</label>
        <div class="col-sm-10">
          <input type="text" class="form-control" id="room" placeholder="Room">
        </div>
      </div>
      <div class="form-group">
        <label for="msg" class="col-sm-2 control-label">Message</label>
        <div class="col-sm-10">
          <input type="text" class="form-control" id="msg" placeholder="Message">
        </div>
      </div>
      <div class="form-group">
        <div class="col-sm-offset-2 col-sm-10">
          <button type="submit" class="btn btn-default">Send</button>
        </div>
      </div>
    </form>
    <ul id="chat"></ul>
  </div>
  <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.2.4/jquery.min.js"></script>
  <script src="/socket.io/socket.io.js"></script>
  <script>
    $(function() {
      // Connect to the specified namespace
      var chat = io('http://localhost:3000/chat?myId=123'),
          news = io('/news');
      $("form").submit(function(e) {
        e.preventDefault();
        // It sends its information to the server.
        chat.emit("chat message", {
          name: $("#name").val(),
          room: $("#room").val(),
          msg: $("#msg").val()
        });
      });
      // When a message is received from the server
      chat.on("chat message", function(data) {
        $("#chat").append($('<li>').text(data));
      });
    });
  </script>
</body>
</html>

this code here