何时可以将socket客户端断开连接

时间:2015-06-23 11:14:16

标签: javascript node.js sockets socket.io client-server

请看下面的代码。它是nodeJS中的一个简单程序。 问题是为什么不打印disconnect? (如果取消注释setTimeout,问题就消失了) 什么是真正的问题?:为什么我不能一起启动socketIO客户端和服务器并在连接后立即关闭套接字?有关与socketIO连接的专业知识是什么?

"use strict";
var Promise = require("bluebird");
var socketio = require("socket.io");
var socketio_client = require("socket.io-client");
var http = require("http");

var port = 7457;
var hostandport = "http://localhost:" + port.toString();

var server = socketio.listen(port);

var client = socketio_client(hostandport);

server.sockets.on("connect", function (socket) {
    console.log("connect");
    socket.on("disconnect", function () {
        console.log("disconnect");
    });

    //setTimeout(function() {
        client.disconnect();
    //}, 1000);
});

2 个答案:

答案 0 :(得分:1)

您错误地设置了服务器,请改为:

var server = require('http').createServer(handler);
var io = require('socket.io')(server);

io.on("connect", function (socket) {
    console.log("connect");
    socket.on("disconnect", function () {
        console.log("disconnect");
    });
//More importantly, you have done this part wrong, 
//the rest of your code may be functional, 
//but it does not adhere to what socket.io sets out in its own API
//(http://socket.io/docs/)
        socket.disconnect();
});

答案 1 :(得分:0)

在Socket.io中,服务器端和/或浏览器端没有连接。只有一个连接。如果其中一侧将其关闭,则将其关闭。因此,您可以使用socket.disconnect()

从服务器关闭它
var app = require('express')();
var http = require('http').Server(app);
var io = require('socket.io')(http);

io.on('connection', function(socket){
  console.log('a user connected');
  socket.on('disconnect', function(){
    console.log('user disconnected');
  });
  setTimeout(function() {
    socket.disconnect();
  }, 1000);
});

转到http://socket.io/get-started/chat/以获得更多说明。