服务器开始运行后,为什么套接字继续在nodejs中无限连接?

时间:2017-09-17 18:57:03

标签: node.js sockets

我是nodejs的新手,为什么套接字会自动连接直到我停止服务器。它应该一次连接一个套接字? 我在浏览器套接字中打开html页面后继续自己连接! 在服务器开始运行后,预计只应连接一个套接字。 如何一次连接一个插座?

server.js

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

users = [];
connections =[];  

server.listen(process.env.port || 3000);
console.log('Server running');
app.get('/',function(req,res){

res.sendFile(__dirname + '/index.html');


   });
     io.sockets.on('connection',function(socket){
  connections.push(socket);
 console.log('Connected: %s sockets connected',connections.length);


socket.on('disconnect',function(data){
    connections.splice(connections.indexOf(socket), 1);
console.log('Disconnected %s sockets connected',connections.length);


   });
  socket.on('send message',function(data){  

    io.sockets.emit('new message',{msg : data});

  });

   });

的index.html

    <!doctype html>
   <html>
  <head>
  <title>Chat</title>
  <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap         /3.3.6/css/bootstrap.min.css">
     <script src="http://code.jquery.com/jquery-latest.min.js"></script>
      <script src="/socket.io/socket.io.js /"></script>
    <style>
     body{

   margin-top:30px;}
 </style>
 </head>

  <body>

  <div class="container">
  <div class="row">
  <div class="col-md-4">
  <div class="well">
  <h3> Online users </h3>
  <ul class="list-group" id="users"> </ul>

  </div>
   </div>
   <div class="col-md-8">
  <div class="chat" id="chat">

   <form id="messageForm">

    <div class="form-group">
     <label>Enter Message</label>
    <textarea  class="form-control" id="message"></textarea>

    </br>
    <input type="submit" class="btn btn-primary"  value="Send message"/>


   </div>
    </form>
  </div>
  </div>

  </div>
  </div>
  </div>

     <script>
    $(function(){
    var socket = io.connect();
    var $messageForm = $('#messageForm');
    var $message = $('#message');
    var $chat = $('#chat');
    $messageForm.submit(function(e){
    e.preventDefault();
    socket.emit('send message',  $message.val());
    $message.val(''); 

    });
    socket.on('new message',function(data){
    $chat.append('<div class="well">'+data.msg+'</div>');
    });

    });
    </script>
    </body>
    </html>

1 个答案:

答案 0 :(得分:0)

这是一个更完整的解决方案,附有一些注意事项。

Socket.io长期以来有过多次连接的snafus。对于诸如客户端和服务器之间的间歇性连接以及过去的错误之类的事情,这可能会发生。

您可能还想在npmjs.com上查看ws,请参阅&gt; https://www.npmjs.com/package/ws

有关模板在NodeJS / Express中如何工作的参考,请参阅&gt; https://expressjs.com/en/advanced/developing-template-engines.html

希望这会让你朝着正确的方向前进......

const express = require('express');
const app = express();
const server = require('http').createServer(app);
const io = require('socket.io').listen(server);
const cons = require('consolidate'); // enables using any template engine.

server.maxConnections = 5; // you can limit connections to server if you wish.

const connections = [];

// Handle your template & engine.
app.engine('html', cons.swig); // where "swig" is the template lang u want to use.
app.set('views', 'your/path/to/views'); // where your views folder lives.
app.set('view engine', 'html'); // the extension of the templates without "."

app.get('/', function (req, res) {
  res.render('index', { /* your locals here */ });
});

io.sockets.on('connection', function (socket) {

  connections.push(socket);
  console.log('Connected: %s sockets connected', connections.length);

  socket.on('disconnect', function (data) {
    connections.splice(connections.indexOf(socket), 1);
    console.log('Disconnected %s sockets connected', connections.length);
  });

  socket.on('send message', function (data) { // wouldn't use event names with spaces
    io.sockets.emit('new message', { // you could do something like 'message:new' & 'message:received' for the above.
      msg: data
    });
  });

});

server.listen(process.env.port || 3000, () => {
  const address = server.address();
  const host = address.address;
  const port = address.port;
  console.log(`Server listening at ${host}:${port}.`);
});

// NOTE: Below handles ctrl-c for Win //
// This will allow for graceful shutdown of connections.
if (process.platform === "win32") { // this is required for handling on windows.
  var rl = require("readline").createInterface({
    input: process.stdin,
    output: process.stdout
  });

  rl.on("SIGINT", function () {
    process.emit("SIGINT");
  });
}

process.on("SIGINT", function () {
  connections.forEach((socket) => {
    // destroy your sockets here!
  });
  process.exit();
});