Testing node httpServer and webSocketServer(ws)
Trying to implement a http-ws server that will close after a client is connected as illustrated below:
var HTTPserver =
httpServer(require('path')
.join(__dirname, 'www'));
HTTPserver
.on('listening', function()
{
console.log('HTTP listening:');
//---------------
var WebSocket = require('ws');
var webSocketServer =
new WebSocket.Server(
{
server: HTTPserver
});
webSocketServer
.on('connection',
function(ws)
{
console.log('client connected');
setTimeout(function()
{
console.log('trying to close webSocketserver');
webSocketServer.close();
setTimeout(function()
{
console.log('trying to close HTTPserver');
HTTPserver.close();
}, 1000);
}, 1000);
});
})
.on('close', function()
{
console.log('server closed'); // never happens
})
.on('error', function()
{
console.log('server error');
})
.listen(8000);
// this works when no Client Connection
/*
setTimeout(function()
{
HTTPserver.close();
}, 3000);
*/
I uploaded the full test project. https://github.com/kenokabe/http-ws-test
HTTPserver.close();
works just as expected without ws
client connections.
HTTPserver.close();
does not work (fails to close) with ws
client connections.
Any idea what is going on and how to fix this issue? Thanks.
**PS. Please note that what I need to close is
NOT only ws
connections but also httpServer.
I need to open and close whole frequently.
The reason to close httpServer is that the project is for plugin, and need to shut down httpServer in a specific case.**
UPDATE
I modified the code to close webSocketServer before httpServer, but still httpServer is alive.