Coder Social home page Coder Social logo

nodejs-websocket's Introduction

Nodejs Websocket

Build Status Inline docs Dependency Status

A nodejs module for websocket server and client

How to use it

Install with npm install nodejs-websocket or put all files in a folder called "nodejs-websocket", and:

var ws = require("nodejs-websocket")

// Scream server example: "hi" -> "HI!!!"
var server = ws.createServer(function (conn) {
	console.log("New connection")
	conn.on("text", function (str) {
		console.log("Received "+str)
		conn.sendText(str.toUpperCase()+"!!!")
	})
	conn.on("close", function (code, reason) {
		console.log("Connection closed")
	})
}).listen(8001)

Se other examples inside the folder samples

ws

The main object, returned by require("nodejs-websocket").

ws.createServer([options], [callback])

Returns a new Server object.

The options is an optional object that will be handed to net.createServer() to create an ordinary socket. If it has a property called "secure" with value true, tls.createServer() will be used instead.

To support protocols, the options object may have either of these properties:

  • validProtocols: an array of protocol names the server accepts. The server will pick the most preferred protocol in the client's list.
  • selectProtocol: a callback to resolve the protocol negotiation. This callback will be passed two parameters: the connection handling the handshake and the array of protocol names informed by the client, ordered by preference. It should return the resolved protocol, or empty if there is no agreement.

The callback is a function which is automatically added to the "connection" event.

ws.connect(URL, [options], [callback])

Returns a new Connection object, representing a websocket client connection

URL is a string with the format "ws://localhost:8000/chat" (the port can be omitted)

options is an object that will be passed to net.connect() (or tls.connect() if the protocol is "wss:"). The properties "host" and "port" will be read from the URL. The optional property extraHeaders will be used to add more headers to the HTTP handshake request. If present, it must be an object, like {'X-My-Header': 'value'}. The optional property protocols will be used in the handshake (as "Sec-WebSocket-Protocol" header) to allow the server to choose one of those values. If present, it must be an array of strings.

callback will be added as "connect" listener

ws.setBinaryFragmentation(bytes)

Sets the minimum size of a pack of binary data to send in a single frame (default: 512kiB)

ws.setMaxBufferLength(bytes)

Set the maximum size the internal Buffer can grow (default: 2MiB) If at any time it stays bigger than this, the connection will be closed with code 1009 This is a security measure, to avoid memory attacks

Server

The class that represents a websocket server, much like a HTTP server

server.listen(port, [host], [callback])

Starts accepting connections on a given port and host.

If the host is omitted, the server will accept connections directed to any IPv4 address (INADDR_ANY).

A port value of zero will assign a random port.

callback will be added as an listener for the 'listening' event.

server.close([callback])

Stops the server from accepting new connections and keeps existing connections. This function is asynchronous, the server is finally closed when all connections are ended and the server emits a 'close' event. The optional callback will be called once the 'close' event occurs.

server.socket

The underlying socket, returned by net.createServer or tls.createServer

server.connections

An Array with all connected clients. It's useful for broadcasting a message:

function broadcast(server, msg) {
	server.connections.forEach(function (conn) {
		conn.sendText(msg)
	})
}

Event: 'listening()'

Emitted when the server has been bound after calling server.listen

Event: 'close()'

Emitted when the server closes. Note that if connections exist, this event is not emitted until all connections are completely ended.

Event: 'error(errObj)'

Emitted when an error occurs. The 'close' event will be called directly following this event.

Event: 'connection(conn)'

Emitted when a new connection is made successfully (after the handshake have been completed). conn is an instance of Connection

Connection

The class that represents a connection, either a client-created (accepted by a nodejs ws server) or client connection. The websocket protocol has two types of data frames: text and binary. Text frames are implemented as simple send function and receive event. Binary frames are implemented as streams: when you receive binary data, you get a ReadableStream; to send binary data, you must ask for a WritableStream and write into it. The binary data will be divided into frames and be sent over the socket.

You cannot send text data while sending binary data. If you try to do so, the connection will emit an "error" event

connection.sendText(str, [callback])

Sends a given string to the other side. You can't send text data in the middle of a binary transmission.

callback will be added as a listener to write operation over the socket

connection.beginBinary()

Asks the connection to begin transmitting binary data. Returns a WritableStream. The binary transmission will end when the WritableStream finishes (like when you call .end on it)

connection.sendBinary(data, [callback])

Sends a single chunk of binary data (like calling connection.beginBinary().end(data))

callback will be added as a listener to write operation over the socket

connection.send(data, [callback])

Sends a given string or Buffer to the other side. This is simply an alias for sendText() if data is a string or sendBinary() if the data is a Buffer.

callback will be added as a listener to write operation over the socket

connection.sendPing([data=''])

Sends a ping with optional payload

connection.close([code, [reason]])

Starts the closing handshake (sends a close frame)

connection.socket

The underlying net or tls socket

connection.server

If the connection was accepted by a nodejs server, a reference to it will be saved here. null otherwise

connection.readyState

One of these constants, representing the current state of the connection. Only an open connection can be used to send/receive data.

  • connection.CONNECTING (waiting for handshake completion)
  • connection.OPEN
  • connection.CLOSING (waiting for the answer to a close frame)
  • connection.CLOSED

connection.outStream

Stores the OutStream object returned by connection.beginBinary(). null if there is no current binary data beeing sent.

connection.path

For a connection accepted by a server, it is a string representing the path to which the connection was made (example: "/chat"). null otherwise

connection.headers

Read only map of header names and values. Header names are lower-cased

connection.protocols

Array of protocols requested by the client. If no protocols were requested, it will be an empty array.

Additional resources on websocket subprotocols:

connection.protocol

The protocol agreed for this connection, if any. It will be an element of connection.protocols.

Event: 'close(code, reason)'

Emitted when the connection is closed by any side

Event: 'error(err)'

Emitted in case of error (like trying to send text data while still sending binary data). In case of an invalid handshake response will also be emited.

Event: 'text(str)'

Emitted when a text is received. str is a string

Event: 'binary(inStream)'

Emitted when the beginning of binary data is received. inStream is a ReadableStream:

var server = ws.createServer(function (conn) {
	console.log("New connection")
	conn.on("binary", function (inStream) {
		// Empty buffer for collecting binary data
		var data = Buffer.alloc(0)
		// Read chunks of binary data and add to the buffer
		inStream.on("readable", function () {
		    var newData = inStream.read()
		    if (newData)
		        data = Buffer.concat([data, newData], data.length+newData.length)
		})
		inStream.on("end", function () {
			console.log("Received " + data.length + " bytes of binary data")
		    process_my_data(data)
		})
	})
	conn.on("close", function (code, reason) {
		console.log("Connection closed")
	})
}).listen(8001)

Event: 'connect()'

Emitted when the connection is fully established (after the handshake)

Event: 'pong(data)'

Emitted when a pong is received, usually after a ping was sent. data is the pong payload, as a string

nodejs-websocket's People

Contributors

asciimike avatar hlovdal avatar hytvi avatar nazar-pc avatar semitrivial avatar sitegui avatar voidvolker avatar williamhogman avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

nodejs-websocket's Issues

Multithreading. How to? Cluster?

Have a large project with this ws server, so now at peak cpu core with process have ~60-70% load.
How to add miltithreading support to this server? Please with example.
Structure is:
Main ws server who accepts all clients connections and this server starts child processes on remote VPS. This remote processes are linked with clients via main ws. ><

Communication - failing to send 12 MB Buffer

I am making a distributed application that sends approx 12 MB of data to worker threads, and I'm trying to do so with nodejs-websocket. Currently I can't tell if the failure is on sending or receiving.

Has this package been tested with larger amounts of data, in the tens of MB?

Would it be worth being clear about what size limits there are for messages?

I am sending with:

connection.send(dataset_envelope_buffer);

Catching ECONNRESET Exception

Hello,

I am on OS X 10.11 and running node v5.3.0. I am running the basic demo app on README.

Whenever a connection is closed, an error of ECONNRESET is thrown and unhandled. I wonder if it is possible to fix the crash?

Connection closed
events.js:141
      throw er; // Unhandled 'error' event
      ^

Error: read ECONNRESET
    at exports._errnoException (util.js:855:11)
    at TCP.onread (net.js:544:26)

I am sorry that because I am rather new to node, I am not sure if I can debug this myself. Thanks in advance!

Adding an extra Authorization header

I'll have to connect to a secure Websocket that uses Basic http authorization.
The only way to do so is to add Authorization to the request header.

'Authorization: Basic ' + new Buffer('name'+ ':' + 'password').toString('base64')

As for now I changed the header string in the startHandshake function.

Would be nice if we could add extra header properties to the ws.connect option?

How add auth?

I want auth on socket with login pass. How add it? Does it lib support it?

Client IP address?

Is there a way to get the IP address of the client from the connection object?

Thanks in advance. I'm using this package as the server component for updates for scripting.com. It's working really well. Thank you.

How would I handle an error when a client disconnects?

I have a node.js server that interfaces with a website, and when I close a tab the server crashes due to an "Unhandled 'error' event"

I assume I need to add an error handler after .listen() but I cant figure out how to do it.

I know this is a noob question but I'm still learning about websockets.

Arduino Connection erro

Hi,

I tried to connect a Arduino client to the ws server. I got

Demo exampe on WSCLient usgae
192.168.1.41
Connected
Get /hallo HTTP/1.1
Upgrade:websocket
Host 192.168.1.21
Sec-WebSocket-Key: eHicPCXz4rJMUscxik7BiWQ==
Sec-WebSocket-Version: 13

Handshak Failed.
Client Disconned.

can I configurate something to get a handshake?

connection.readyState is always 1

Hi there,
My websock server runs well but when I check readyState of my disconnected devices they are still assigned as 1.

What am I missing to do?

Thanks pal.

Broadcast not working

My Code:

var ws = require("nodejs-websocket")


var server = ws.createServer(function (conn) {
    console.log("New connection")
    conn.on("text", function (str) {
        //console.log("Received "+str)
         obj = JSON.parse(str);


         x = obj.x
         y = obj.y
         server = obj.server
         cells = obj.cells
         color = obj.color
         nick = obj.nick


         playerData1 = JSON.stringify({x: x, y: y, server: server, cells: cells, color: color, nick: nick});
         console.log(playerData1);
         conn.send(playerData1)
        broadcast(playerData1);
    })



    conn.on("close", function (code, reason) {
        console.log("Connection closed")
    })




}).listen(8001)


function broadcast(str) {
    server.connections.forEach(function (conn) {
        conn.sendText(str)
    })
}

the error:

TypeError: Cannot read property 'forEach' of undefined
at broadcast (C:\Users\shzd1\Desktop\Minimap Server\server.js:38:20)
at Connection. (C:\Users\shzd1\Desktop\Minimap Server\server.js:22:4)
at emitOne (events.js:77:13)
at Connection.emit (events.js:169:7)
at Connection.processFrame (C:\Users\shzd1\Desktop\Minimap Server\node_modules\nodejs-websocket\Connection.js:558:9)
at Connection.extractFrame (C:\Users\shzd1\Desktop\Minimap Server\node_modules\nodejs-websocket\Connection.js:499:14)
at Connection.doRead (C:\Users\shzd1\Desktop\Minimap Server\node_modules\nodejs-websocket\Connection.js:239:23)
at Socket. (C:\Users\shzd1\Desktop\Minimap Server\node_modules\nodejs-websocket\Connection.js:55:8)
at emitNone (events.js:67:13)
at Socket.emit (events.js:166:7)

Max call stack size exceeded on Connection.close

I have a periodic service in nodejs that tries to create 30-40 socket connections and close it in case (it gets connected successfully or some error occurs while connecting) but every now an then I get Maxmimum call stack size exceeded error at line connection.close()

My Code structure

const connection = ws.connect(socketServerUrl, (err) => {
    if (err) {
        // console.log the error
    }
    else {
        connection.sendPing();
    }
});

connection.on('error', (err) => {
    const reason = err && err.message ? err.message : err;

    // THIS IS WHERE I GET THAT MAX CALL STACK SIZE REACHED EXCEPTION
    connection.close(); // release the connection
});

connection.on('pong', (data) => {
    connection.close(); // release the connection
});

Error Screenshot
image

WS on sencha connect

Is it possible to integrate nodejs-websocket with connect (or express) https server to run on the same port?

Suggestion: alias 'send' to 'sendText'

Love the simplicity - Zen style - of this solution. I would like to suggest to create an alias to 'sendText' so to be in line with other libraries - they use 'send' as the default for text messages.

It is a minor request but well, I thought to make this suggestion

Client losing connection after a few messages

var ws = require("nodejs-websocket")
var playercounter= new Array(101);
playercounter.fill(0)
var giveID=0
var disconnectthis
var string
var numberofplayers=0
var serverfull=false
var playersalive=0


var server = ws.createServer(function (connection) { 
	connection.playerid = null
	connection.on("text", function (str) {
		if(str==="ping"){
			console.log("pinged")
			connection.sendText("online")
			connection.close()

		}
		else if (connection.playerid === null) {

			for(var i=1;i<=101;i++){
				if(i===101){
					connection.sendText("serverfull")
					console.log("Server is full")
					connection.close()

				}else if(playercounter[i]===0 && i<101){
					giveID=i
					playercounter[i]=1
					i=101
					
				}

			}
			connection.playerid = giveID
			numberofplayers++
			playeralive++
			for(var o=1;o<101;o++){
				if(playercounter[o]===1){
					connection.send("spawn:"+Number(playercounter[o]))
				}
			}			
			connection.sendText("id:"+giveID)
			broadcast("spawn:"+giveID)
			
			console.log("New player joined, ID:"+giveID)
			
			broadcast("eventid:"+giveID)

			if(numberofplayers>=10){

				setTimeout(()=>{broadcast("begin")
				serverlock=true
			},3000)
			}

		}
		else if(str.startsWith("arrow")){
			broadcast(str)
		}
		else if(str.startsWith("dead")){
			broadcast(str)
			playeralive--
		}

		 else
		 			broadcast("update:"+connection.playerid+":"+str)
	})

	connection.on("close", function(msg){
		numberofplayers--
		playeralive--
		disconnectthis=Number(connection.playerid)
		playercounter[disconnectthis]=0
		broadcast("dead:"+connection.playerid)
console.log("Player under ID "+connection.playerid+" disconnected")
	})

}).listen(80) 

function broadcast(str) {
	server.connections.forEach(function (connection) {
		connection.sendText(str)
	})
}
console.log("Server running!")
console.log('Type "kick <id>" to kick a player from the server, or "close" to close the server.')

I'm using the code above to build a server. The problem is, after a few messages(sometimes, after the first one), the client loses connection(No matter the client, message, browser,etc), throwing no error on client nor server side, only giving code 1002 and firing a close event to the client(server doesn't fire).

Client side disconnection message:
https://i71.servimg.com/u/f71/15/27/47/75/sem_tz13.png

Why? I've tried to find bugs for HOURS on any side, and there are NONE.

Websocket Idle Timeout

Hi,
I've created a simple websocket server with nodejs-websocket module to test just another web client (which is written by me)

In my server-side logic, I'm sending ping to client-side in a timer interval. (The timer interval can be set from client-side) For short intervals (for example 15 - 30 seconds) ping/pong communication continues properly. When I'm trying to set the timer interval to 15 minutes, ping/pong isn't working. I think, connection is closed by the server side.

Which part I'm missing? Is there a websocket idle timeout on server-side? If there is, what is the timeout? Could you please share information about that?

Maximum frame size issue

connection closed: Received frame size of 1048879exceeds maximum accepted frame
size of 1048576

项目如何启动

你这个项目到底是怎么运行的,能不能写个中文文档出来?????

Keep Alive?

Hi there,

I am currently using this for a work project, I am struggling to see why I keep getting this issue:
'This socket has been ended by the other party', I assume it needs some kind of keep alive? or is this already included with this?

Thanks,
Danny

New SSL Cert without stopping server?

Sorry, not really an issue but a question: am I correct that there is no way of hot-swapping the SSL cert used when creating a new server, hence the server has to be destroyed and re-created?

eval(string) is making connection be lost after second message received

In my application, if I use eval to execute code that is inside a string, inside the conn.on part, it loses connection right after receiving the second message(and doesn't execute it too)

conn.on("text", function (str) {
eval(stringInsideVariable)
})

(that is inside a code which is pretty much the same as the example given in this github)

And I can't find a way around it, since I need that eval to execute the conn.sendText() if it is inside the string(which I don't know, it will depend on who's using my application)

-Is there a way to send a message back to the user from outside the function given as example?
-Why is it disconnecting ?

WSS does not allow to establish a connection

Hi,

I'm Testing WS and WSS servers using this module. It works fine with a regular WebSocket connection, but throws an error when trying to establish a secure connection:

Client: Connection aborted
Request:
(
GET / HTTP/1.1
Host: 127.0.0.1:8001
User-Agent: Mozilla/5.0 (Windows NT 6.0; WOW64; rv:23.0) Gecko/20100101 Firefox/23.0
Sec-WebSocket-Version: 13
Origin: https://127.0.0.1
Sec-WebSocket-Key: n9MrJXMtVyD61RUHhwejcw==
Connection: keep-alive, Upgrade
Pragma: no-cache
Cache-Control: no-cache
Upgrade: websocket
)

Server:
events.js:72
throw er; // Unhandled 'error' event
Error: read ECONNRESET
at errnoException (net.js:901:11)
at TCP.onread (net.js:556:19)

Server code:

var useTSL = true;
function createWebSocket() {
var wsOptions = useTSL ? {
secure: true,
key: fs.readFileSync('https/key.pem'),
cert: fs.readFileSync('https/cert.pem')
} : { };
ws.createServer(wsOptions, function (conn) {
conn.on("text", function (str) {
conn.sendText(str.toUpperCase() + "!!!");
});
conn.on("close", function (code, reason) { });
conn.on("error", function (error) { });
}).listen(8001, "127.0.0.1");
}

Client code:
var wsUri = "wss://127.0.0.1:8001";
websocket = new WebSocket(wsUri);
websocket.onopen = function(evt) { onOpen(evt) };
websocket.onclose = function(evt) { onClose(evt) };
websocket.onmessage = function(evt) { onMessage(evt) };
websocket.onerror = function(evt) { onError(evt) };

NodeJS: 0.10.18.0

Are query parameters supported?

The WebSocket specification states that this is a valid websocket URI:
ws://myserver.com/path?param=1

However I am unsure if nodejs-websocket supports access to the URI parameters.

Can anyone tell me if this is supported (and if yes, how to use it)?

Thanks

Run paired with a Node http/https server?

Is there a way to hand ws an http.createServer() / https.createServer() instance, so that a server can handle (limited) HTTP traffic in addition to upgrading a connection to a websocket connection on a specific route?

For instance:

const https = require('https');
const ws = require('node-websocket');
const routes = require('./routes.js');
const server = https.createServer(routes);
ws.setUpgradePath(server, 'join', connection => {
  connection.on( ... )
  ...
});
server.listen(80);

So we have a simple secure http server, with a route that clients can use when creating websockets in order to set up the two way persistent connection, while also being able to load up (for example) a lobby page on the / route that gives them information on who else is already connected, a button that starts their own websocket client code, etc.

Especially for debugging and administration, being able to generate a webpage that shows the current server state on the same address and port (but not path), rather than using a separate server entirely, is fairly crucial.

undocumented net.Socket `readable` event and `read` method?

Hi,

Great work here!

And I'm just curious when read somewhere in your src that like:

    socket.on('readable', function () {
        that.doRead()
    })
...
Connection.prototype.doRead = function () {
    var buffer, temp

    // Fetches the data
    buffer = this.socket.read()
...

But I digged NodeJS api docs up to 0.10, there's no such event as readable and method as read documented. I'm curious whether they are legacies or just undocumented artifacts.

Don't know if its proper to ask the question as an issue, you're free to close it.

Regards & thanks,
Compl

Get Connection IP

Hi,

I can't find a way in which I can get the ipv4 address of a new connection.

Is there a way for doing this?

Thanks in advance

The client doesn't recognise server response when the text from the server is immediate

I've tried to implement some simple scenario when the server sends some text to the client immediately after the connection.

The (simplified) server looks like:

var ws = require("nodejs-websocket");
var wserver = ws.createServer(function (conn) {
    console.log("New connection");
    setTimeout(function(){
        conn.sendText(JSON.stringify({
            type:'hello'
        }));
    },0);
    conn.on("close", function (code, reason) {
        console.log("Connection closed");
    })
})

wserver.listen(8001);

The (simplified) client looks like:

var ws = require("nodejs-websocket");

var conn = ws.connect("ws:127.0.0.1:8001",function() {
    console.log("New connection");

    conn.on("close", function (code, reason) {
        console.log("Connection closed")
    })
    conn.on("error", function (err) {
        console.log("Connection ERROR!",err)
    })
});

When the first client connects to the server it looks fine, the client prints "New connection"

But when the second (and all following) client connects to the server, the client doesn't recognise a connection readyness (i.e. doesn't print "New connection" message).

The server recognises and reports the both connections.
The network traffic grabbed by the wireshark looks the same (except security cookies).

The only difference is a time between last server handshake packet and the text packet sent from the server after the handshake.

To check the problem, I've tried two cases:

  1. I've removed immediate text send from the server code. The bug disappeared.
  2. I've changed timeout from 0 to 100 to delay a text send. The bug disappeared.

From my point of view it might be caused by some inconsistency in the client code, when the client doesn't separate a server handshake packet from the next packet if it follows immediately to the last websockets handshake packet and concatenated by the TCP layer to one piece of data sent to the user layer.

Server Messages are not broadcasting to all clients

I'm trying to create a websocket from Client side and send messages from server node-js.
When ever i receive a message from client, it brodcast well.
But if i send a message from server to all the clients, it is not brodcasting.

below is my code.
var wsCallback = function(connection) {
connection.nickname = null
connection.on("text", function (str) {
connection.nickname = str
broadcasting(str);
})
connection.on("close", function () {
broadcasting(connection.nickname+" left")
})
};

var server = ws.createServer(wsCallback)
server.listen(8081,'localhost')

function broadcasting(str) {
console.log(server.connections.length);
server.connections.forEach(function (conn) {
conn.sendText(str)
})
}

when i call broadcasting from some other method, it is not broadcasting, it says the no of connection is 0.But if i send a message from one of the clients, then that message is broadcasting.

I don't know, what i'm missing. Looks like a referencing issue.

could you please help me solve this issue.

trying to send typed array : Float32Array - how reassemble back once received

Your library works fine when sending typed arrays like Uint8Array, however when I try to send a float typed array like Float32Array, the data comes across from client to server however it arrives with BYTES_PER_ELEMENT of 1 instead of desired BYTES_PER_ELEMENT of 4. Do I need to roll my own logic to reassemble my float array from the underlying single byte size data element array ? or can I use your library for this reassembly final step ?

Unable to create an https server ...

When I add the "secure": true option to the createServer call in order to create an HTTPs based server and then send in a wss request, I get the error logged:

WebSocket connection to 'wss://localhost:3000/' failed: Error in connection establishment: net::ERR_SSL_VERSION_OR_CIPHER_MISMATCH

When I try and hit localhost:3000 using a browser, I get the same error. I am using the latest version of Chrome.

wss:// and SSL Issues

If I try to connect via wss://url, the code fails with the following error:

Error: 140735134868240:error:140770FC:SSL routines:SSL23_GET_SERVER_HELLO:unknown protocol:../deps/openssl/openssl/ssl/s23_clnt.c:787:

at SlabBuffer.use (tls.js:232:18)
at CleartextStream.read [as _read] (tls.js:452:29)
at CleartextStream.Readable.read (_stream_readable.js:320:10)
at EncryptedStream.write [as _write] (tls.js:366:25)
at doWrite (_stream_writable.js:226:10)
at writeOrBuffer (_stream_writable.js:216:5)
at EncryptedStream.Writable.write (_stream_writable.js:183:11)
at write (_stream_readable.js:582:24)
at flow (_stream_readable.js:591:7)
at Socket.pipeOnReadable (_stream_readable.js:623:5)

Pretty sure this error is related to the fact that this line has the ports backwards in the ternary operator. It should be (secure ? 443 : 80) rather than the way it currently is, correct? That being said, when I switch it and run it, it fails to connect and keeps trying to reconnect (but at least it doesn't error out). I wanted to get some confirmation on this before I do a PR (especially since it doesn't work when I switch it).

Error during WebSocket handshake: Sent non-empty 'Sec-WebSocket-Protocol' header but no response was received

I'm trying to build a WebSocket server implementation of Guacamole, which sends the following headers:

  headers:
   { host: 'localhost:8889',
     connection: 'Upgrade',
     pragma: 'no-cache',
     'cache-control': 'no-cache',
     upgrade: 'websocket',
     origin: 'http://localhost:8000',
     'sec-websocket-version': '13',
     'user-agent': 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_11_1) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/48.0.2564.116 Safari/537.36',
     'accept-encoding': 'gzip, deflate, sdch',
     'accept-language': 'de-DE,de;q=0.8,en-US;q=0.6,en;q=0.4',
     'sec-websocket-key': 'ipg7rRB525W3Cv67MY5x0g==',
     'sec-websocket-extensions': 'permessage-deflate; client_max_window_bits',
     'sec-websocket-protocol': 'guacamole' },

The handshake response from the server should then contain

Sec-WebSocket-Protocol: guacamole

However it doesn't, thus resulting in this error.

I have found a mention of this error in #24, but it was closed as the original author didn't reply.

not clear on how server can receive binary from client

I would like to use your library to allow my browser client side to send to node-js server side binary data in form of a typed array such as Uint8Array. I am successfully sending normal text from client to server. When attemping binary, here is my client side send

socket.binaryType = 'arraybuffer';
socket.send(big_monster_data);

and here is my nodejs-websocket server side which is NOT correctly receiving the client sent data

var server = ws.createServer(function (connection_request) {

// here is text which is received just fine
connection_request.on("text", function (received_data) {
        console.log("Received text format : " + received_data);
        connection_request.sendText(received_data.toUpperCase()+" OK");
    });

// here is attempt at binary which is not working
connection_request.on("binary", function (received_data) {

// below gets printed YET length is undefined
console.log("Received binary format of length ", received_data.length);

    if (received_data instanceof ArrayBuffer) {

        // this is NOT getting reached
        console.log("OK instanceof ArrayBuffer");
    }

    // HERE I want to do something with received arraybuffer
}

}

thank you for your time

cheers, Scott Stensland

A better demo app

I've learned a bunch about WebSockets in the last couple of weeks, including getting them up and running at some scale for readers of my blog, scripting.com.

But I couldn't figure out from the various demos and docs how to create a server that knew when the client had disappeared, and vice versa, how to program a client to reconnect after the server came back after going down.

So I did a bit of trial and error, and then packaged it up in a GitHub repo, hoping people with a detailed understanding of WebSockets would review it and tell me:

  1. Is this right?
  2. Is there a better way to do the same thing?

Here's the sample code..

https://github.com/scripting/betterWebSocketsDemo

Any feedback would be most welcome. I really want to get this right, and then of course share what I've learned.

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.