Skip to content

Commit

Permalink
Avoid errors when connection is reset (as when using self-signed cert…
Browse files Browse the repository at this point in the history
…ificate for wss)
  • Loading branch information
sitegui committed Sep 11, 2013
1 parent 4a7f953 commit a48eedc
Show file tree
Hide file tree
Showing 4 changed files with 61 additions and 1 deletion.
6 changes: 6 additions & 0 deletions 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
Expand All @@ -16,13 +18,17 @@ 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 () {
var pos = that.connections.indexOf(conn)
if (pos != -1)
that.connections.splice(pos, 1)
})

// Ignore errors before the connection is established
conn.on("error", nop)
}

if (secure)
Expand Down
2 changes: 1 addition & 1 deletion package.json
@@ -1,6 +1,6 @@
{
"name": "nodejs-websocket",
"version": "0.1.1",
"version": "0.1.2",
"author": "Sitegui <sitegui@sitegui.com.br>",
"description": "Basic server&client approach to websocket (text and binary frames)",
"main": "./index.js",
Expand Down
39 changes: 39 additions & 0 deletions samples/wss/index.html
@@ -0,0 +1,39 @@
<!DOCTYPE HTML>
<html>
<head>
<meta charset="utf-8">
<title>Simple websocket secure test</title>
<script>
var conn = new WebSocket("wss://127.0.0.1:8001")

conn.onopen = function () {
console.log("Connection opened")
conn.send("hello world")
}

conn.onclose = function () {
console.log("Connection closed")
}

conn.onmessage = function (evt) {
console.info("Received "+evt.data)
conn.close()
}

conn.onerror = function () {
console.error("Error")
}
</script>
</head>

<body>
<p><strong>Notes:</strong></p>
<ol>
<li>Open web console</li>
<li>Run index.js script with nodejs</li>
<li>Access "https://127.0.0.1:8001" in another tab. The browser should alert you about security, since the certificate is self-signed</li>
<li>Accept security exception and close that tab</li>
<li>Reload this page</li>
</ol>
</body>
</html>
15 changes: 15 additions & 0 deletions 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")

0 comments on commit a48eedc

Please sign in to comment.