2017-09-17 15 views
0

私はnodejsを初めて使用しています。ソケットを一度に1つずつ接続する必要があります。 ブラウザのソケットでhtmlページを開いた後も、自分で接続しています! サーバーの起動後に接続するソケットは1つだけにする必要があります。 一度に1つのソケットを接続するにはどうすればよいですか?ここでサーバが起動した後、ソケットがnodejで無限に接続され続けるのはなぜですか?

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> 

答えて

0

はあなたのためにいくつかのメモと、もう少し完全なソリューションです。

Socket.ioには長い間、複数の接続を持ついくつかの詮索がありました。これは、過去のバグに対するクライアントとサーバー間の断続的な接続などの場合に起こる可能性があります。

またnpmjs.com上のチェックアウトのWSはhttps://expressjs.com/en/advanced/developing-template-engines.html

がうまくいけば、これが正しい方向にあなたを配置します>参照テンプレートはNodeJS/Expressでどのように機能するかについてのいくつかの参考のために>https://www.npmjs.com/package/ws

を参照することもできます...

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(); 
}); 
関連する問題