From a48eedc8e892d19ee115f81ce4cb67ea8674062b Mon Sep 17 00:00:00 2001 From: Guilherme Souza Date: Tue, 10 Sep 2013 21:47:19 -0300 Subject: [PATCH] Avoid errors when connection is reset (as when using self-signed certificate for wss) --- Server.js | 6 ++++++ package.json | 2 +- samples/wss/index.html | 39 +++++++++++++++++++++++++++++++++++++++ samples/wss/index.js | 15 +++++++++++++++ 4 files changed, 61 insertions(+), 1 deletion(-) create mode 100644 samples/wss/index.html create mode 100644 samples/wss/index.js diff --git a/Server.js b/Server.js index bb1c448..5243653 100644 --- a/Server.js +++ b/Server.js @@ -1,5 +1,7 @@ // Represents a websocket server +function nop() {} + // new Server() creates a new ws server and starts listening for new connections // Events: listening(), close(), error(err), connection(conn) // secure is a boolean that indicates if it should use tls @@ -16,6 +18,7 @@ function Server(secure, options, callback) { var onConnection = function (socket) { var conn = new Connection(socket, that, function () { that.connections.push(conn) + conn.removeListener("error", nop) that.emit("connection", conn) }) conn.on("close", function () { @@ -23,6 +26,9 @@ function Server(secure, options, callback) { if (pos != -1) that.connections.splice(pos, 1) }) + + // Ignore errors before the connection is established + conn.on("error", nop) } if (secure) diff --git a/package.json b/package.json index e855d40..9fea456 100644 --- a/package.json +++ b/package.json @@ -1,6 +1,6 @@ { "name": "nodejs-websocket", - "version": "0.1.1", + "version": "0.1.2", "author": "Sitegui ", "description": "Basic server&client approach to websocket (text and binary frames)", "main": "./index.js", diff --git a/samples/wss/index.html b/samples/wss/index.html new file mode 100644 index 0000000..f6bd508 --- /dev/null +++ b/samples/wss/index.html @@ -0,0 +1,39 @@ + + + + +Simple websocket secure test + + + + +

Notes:

+
    +
  1. Open web console
  2. +
  3. Run index.js script with nodejs
  4. +
  5. Access "https://127.0.0.1:8001" in another tab. The browser should alert you about security, since the certificate is self-signed
  6. +
  7. Accept security exception and close that tab
  8. +
  9. Reload this page
  10. +
+ + diff --git a/samples/wss/index.js b/samples/wss/index.js new file mode 100644 index 0000000..47c4c5e --- /dev/null +++ b/samples/wss/index.js @@ -0,0 +1,15 @@ +var fs = require('fs') +var ws = require('../../') + +// See http://www.nodejs.org/api/tls.html for info on how to create key and certificate files +var options = { + secure: true, + key: fs.readFileSync("key.pem"), + cert: fs.readFileSync("cert.pem") +} + +ws.createServer(options, function (conn) { + conn.on("text", function (str) { + conn.sendText(str.toUpperCase() + "!!!") + }) +}).listen(8001, "127.0.0.1")