binaryjs client crashes when server restarts - javascript

I'm using binaryjs to implement a video transfer program between node.js server and node-webkit client.The client stays connected,once a video is uploaded,the client starts downloading it.
It works fine generally,the client does get the videos.But the client throws an error and crashes when the server restarts or crashes. I have been listening the BinaryClient 'error' & 'close' event,however it doesnot works.
I guess maybe i'd listen 'error' event from something else.What to do to fix the problem?Anyone can help?
Thanks a lot!
app.js:
var BinaryServer = require('binaryjs').BinaryServer;
var server = http.createServer(app).listen(3000);
var binaryServer = new BinaryServer({ server: server, path: '/binary' });
binaryServer.on('connection', function (client) {
// client on stream
// client on close
// client on error
});
// binaryServer on error
client:
var BinaryClient = require('binaryjs').BinaryClient;
var binaryClient = new BinaryClient('ws://127.0.0.1:3000/binary');
binaryClient.on('open', function () {
// binaryClient.createStream( ... )
});
// binaryClient on stream
// binaryClient on close
// binaryClient on error
error:
Uncaught node.js Error
Error: read ECONNRESET
at exports._errnoException (util.js:742:11)
at TCP.onread (net.js:541:26)

Related

Chrome WebSocket connection closes immediately

I have been trying to setup a wss server using nodejs, and have encountered a problem when trying to connect to it using chrome. The problem still occurs with all extensions disabled and in an incognito window so I've ruled that out as the problem.
When trying to connect using chrome, I get the error:
WebSocket connection to 'wss://www.domain-name.com/' failed:
with no reason given. On the server, socket.on('close') is called immediately with description "Connection dropped by remote peer" The close event has wasClean = false. This error does not occur when connecting from safari and Firefox so I'm not really sure where to look to see what's causing it. It's running on AWS Lightsail, and through an Apache proxy server.
The client code:
var socket = new WebSocket("wss://www.domain-name.com", 'JSON')
socket.onopen = function (event) {
console.log('open');
socket.send('socket opened')};
socket.onclose = function (event) {
console.log(event)};
socket.onmessage = function(message) {
console.log('receiving message from server...')};
And the server code:
const WebSocketServer = require('websocket').server;
app = express()
var server = app.listen(3000, () => {
console.log('Server started');
});
app.use(express.static('public'));
var wsServer = new WebSocketServer({
httpServer: server
});
wsServer.on('request', function(request){
console.log('New connection');
var connection = request.accept(null, request.origin);
connection.send('welcome from server...');
connection.on('message', function(message){
console.log(message)};
connection.on('close', function(reasonCode, description) {
console.log('disconnecting', reasonCode, description);
});
});
I also got the same error before switching to a secure WebSocket server. Any help would be appreciated, I've run out of places to look and ways to try and get more information to help out what the problem is.
EDIT: it seems to work on chrome on my phone, but not on chrome on my friends phone?
The problem was not specifying the protocol when accepting the connection. After about 20 hours working on the same bug and implementing an SSL certificate to get it to work, I changed:
request.accept(null, request.origin);
to:
request.accept('json', request.origin);
For some reason the chrome gives a really unhelpful error message. Microsoft edge the same error occurs, but gives a much more helpful error message so I could work out what was going on.
In my case, this was caused by passing an unused options value as the third parameter to the WebSocket constructor. The options parameter is supported by Node.js's ws module but not by browsers; however, instead of displaying a clean error message, Chrome closed the connection without a good description.

Handling an error on a tcp connection using the "net" module of NodeJS

Im trying to learn the "net" module of NodeJS, but i have run into an annoying problem. My code is in 2 scripts.
//index.js
var net = require("net")
var server = net.createServer(socket=>{
socket.write("Hello!")
})
server.on("error", err=>{
console.error(err)
})
server.listen(50001)
and
//client
var net = require("net")
net.createConnection({
host:"localhost",
port: 50001
})
.on("data", data=>{
console.log(data.toString())
})
when i run the 2 scripts...
node index.js
node client.js
...the message "Hello!" is sent to the client with no problems. If i CTRL+C out of the client (to simulate an unexpected closure), i get the following error
events.js:174
throw er; // Unhandled 'error' event
^
Error: read ECONNRESET
at TCP.onStreamRead (internal/stream_base_commons.js:111:27)
Emitted 'error' event at:
at emitErrorNT (internal/streams/destroy.js:82:8)
at emitErrorAndCloseNT (internal/streams/destroy.js:50:3)
at process._tickCallback (internal/process/next_tick.js:63:19)
which i find strange, as I have registered an "error" event on the server. What am i doing wrong?
The program registers a handler for an 'error' event on the server's listening socket, but it does not register an 'error' handler on the separate new socket that is created to carry the connection that is made by the client. (Every connection to the server gets a separate new socket, distinct from the listening socket and from any other connections that have been made earlier.)
That new connection socket is the one that is passed as the argument to the server's connect handler. It's the socket that you write 'Hello!' into.
If you want the program to be notified of an error on that new socket then you must register an 'error' handler on the new socket. Something like this:
var net = require("net")
var server = net.createServer(socket=>{
socket.on('error', err=>{
console.error('connected socket: ' + err);
});
socket.write("Hello!")
})
server.on("error", err=>{
console.error(err)
})
server.listen(50001)
Similarly, if you wanted the server to read data from the connection then you would register a handler for the 'data' event on the new connection socket, in the same way as you already did on the client's socket.

Beginner Node.JS net.createServer example

I am an old PERL coder trying to learn node.JS programming. I have question about the code I am writing to create a socket connection between a server and a client app.
The code below works. But I do not know how to accept data sent from the client to the server.
Basically what I want to do is very simple. Client connects to a Server listening on a socket, sends some information, which the Server reads and then sends information back to the Client. The only part I am not understanding is how to get the Server side to read/accept/display the data string sent from the Client.
Can someone please point me in the right direction?
Thank you for your help in advance.
(My apologies for being ignorant.)
Here is the server side code:
var net = require('net');
var server = net.createServer(function(socket) {
// confirm socket connection from client
console.log((new Date())+'A client connected to server...');
socket.on('data', function(data) {
var json = JSON.parse(data.toString());
console.log(json)
});
// send info to client
socket.write('Echo from server: NODE.JS Server \r\n');
socket.pipe(socket);
socket.end();
console.log('The client has disconnected...\n');
}).listen(10337, '192.168.100.1');
Here is the client code:
var net = require('net');
var client = new net.Socket();
client.connect(10337, '192.168.100.1', function() {
console.log('Connected'); // acknowledge socket connection
client.write('Hello, server! Love, Client.'); // send info to Server
});
client.on('data', function(data) {
console.log('Received: ' + data); // display info received from server
client.destroy(); // kill client after server's response
});
client.on('close', function() {
console.log('Connection closed');
});
I get an error on the server when I do this where it says the string sent from the client is an invalid token. here is the error message.
undefined:1
Hello, server! Love, Client.
^
SyntaxError: Unexpected token H
at Object.parse (native)
at Socket.<anonymous> (/root/nodejs/server-example.js:7:19)
at Socket.emit (events.js:117:20)
at Socket.<anonymous> (_stream_readable.js:765:14)
at Socket.emit (events.js:92:17)
at emitReadable_ (_stream_readable.js:427:10)
at emitReadable (_stream_readable.js:423:5)
at readableAddChunk (_stream_readable.js:166:9)
at Socket.Readable.push (_stream_readable.js:128:10)
at TCP.onread (net.js:529:21)
I was being stupid. I found the answer I was looking for. And it was very simple.
Here is what I should have written in place of the JSON statements
socket.on('data', function(data) {
var string = (data.toString());
console.log(string)
});
or handle both JSON and Strings that get written to the socket:
socket.on('data', function(data) {
try {
var obj = JSON.parse(data.toString())
console.log(JSON.stringify(obj, null, 4))
}
catch(e) {
var string = data.toString()
console.log(string)
}
})

Firefox Nodejs Websocket

I am using Aurora 17, Chrome 22 and Firefox 16 and I am trying to create a simple chat app. I am using Node 0.8.9.
Firefox is getting the error that it cannot connect giving the error
Firefox can't establish a connection to the server at ws://localhost/.
I also tried it with the port and it have the same message
Firefox can't establish a connection to the server at ws://localhost:4444/.
Here is my code:
Server Code:
var http = require('http');
var net = require('net');
function onRequest(req, res) {
// Does enough to render a page and javascript
}
http.createServer(onRequest).listen(4444);
var socket = new net.Socket();
socket.connect(4444, "localhost", function(){
console.log("Socket Connected");
});
socket.on("message", function(message){
console.log(message);
});
Client Code:
var WebSocket = window.WebSocket || window.MozWebSocket;
var connection = new WebSocket('ws://localhost:4444');
connection.onopen = function() {
// Never runs
alert("This never runs :(")
}
connection.onerror = function(error) {
// Always runs here
console.log(error)
}
I get an output that the Socket is connect from the log statement on the server but Firefox cannot connect to the socket.
On Chrome, there is no error but the "onopen" is never fired. Using connection.send("a message") does not send anything to the server and returns false.
You're creating an ordinary TCP client socket in your server code and connecting it to your HTTP server. That's not at all the same thing as creating a WebSocket server that a browser can connect to. Use a library designed for the purpose (socket.io is very commonly used, since it can fall back to alternate transports when a browser doesn't support WebSockets).

"Error: write EPIPE" with Socket.io on node.js

I manually applied this patch and everything works now. Waiting on upstream to fix this
https://github.com/LearnBoost/socket.io-client/pull/361/files
I'm just trying to follow the examples given and trying to get this to work.
Mockserver.js:
var io = require('socket.io').listen(8000);
io.sockets.on('connection', function(client) {
console.log('+ new client');
client.on('disconnect', function() {
console.log('- lost a client');
});
});
Mockclient.js:
var io = require('socket.io-client');
var socket = new io.connect('localhost', { port: 8000 });
socket.on('connect', function() {
console.log('connected');
});
socket.on('message', function(data) {
console.log(data);
});
I then run these pair with node Mockserver.js and node Mockclient.js on another terminal
info - socket.io started
debug - client authorized
info - handshake authorized 14797776461130411158
debug - setting request GET /socket.io/1/websocket/14797776461130411158
debug - set heartbeat interval for client 14797776461130411158
debug - client authorized for
debug - websocket writing 1::
+ new client
debug - set close timeout for client 14797776461130411158
***************************** error occurs here ****************
info - socket error Error: write EPIPE
at errnoException (net.js:632:11)
at Object.afterWrite [as oncomplete] (net.js:470:18)
****************************************************************
debug - setting request GET /socket.io/1/xhr-polling/14797776461130411158?t=1325912082073
debug - setting poll timeout
debug - discarding transport
debug - cleared close timeout for client 14797776461130411158
debug - cleared heartbeat interval for client 14797776461130411158
debug - clearing poll timeout
info - transport end
debug- set close timeout for client 14797776461130411158
debug - cleared close timeout for client 14797776461130411158
at this point I stopped Mockclient.js
- lost a client
debug - discarding transport
The only output for "node Mockclient.js" is
The "sys" module is now called "util". It should have a similar interface.
What's causing the socket exception? I'm probably missing something pretty obvious. Also, can somebody else try my code to see if the errors on their machine as well? The code inside socket.on('connect'... isn't triggering either. I don't exactly know why.
Apply this patch
https://github.com/LearnBoost/socket.io-client/pull/361/files

Categories

Resources