The Node.JS server doesn't receive the message quickly..
Server code:
var WebSocketServer = require("ws").Server
var http = require("http")
var express = require("express")
var app = express()
var port = process.env.PORT || 5000
app.use(express.static(__dirname + "/"))
var server = http.createServer(app)
server.listen(port)
console.log("http server listening on %d", port)
var wss = new WebSocketServer({server: server})
console.log("websocket server created")
wss.on("connection", function(ws) {
var id = setInterval(function() {
ws.send(JSON.stringify(new Date()), function() { })
}, 1000)
console.log("websocket connection open")
ws.on("message", function(msg){
ws.send(msg);
})
ws.on("close", function() {
console.log("websocket connection close")
clearInterval(id)
})
})
Code to connect:
var z = new WebSocket("ws://appname.herokuapp.com/");
z.onopen = function(){ console.log("opened"); };
// ... after opened message seen in console, the following
// were typed directly into the console, a few seconds apart
z.send("H");
z.send("Hello World");
z.send("Hello World asdf");
Until the third send was done (even if it was a minute after the others), the server did not respond with H or Hello World; all three responses were made at the same time. How do I make the server respond in a timely manner?
(Using WireShark, I checked that the sends were actually done; they were)
Edit: The amount of requests/time before response varies each time.
Related
In my Node.js + Socket.io application, I'm trying to set the ping timeout to 63 seconds (63 seconds of inactivity allowed until the connection between the server and the client(s) is considered closed). Unfortunately, when I run my code below, I get the following error:
var io = socket(server);
^
TypeError: socket is not a function
Below is my code:
var express = require("express");
var socket = require("socket.io")(3000, {
pingTimeout: 63000,
});
var app = express();
var server = app.listen(3000);
app.use(express.static("public"));
var io = socket(server);
just remove this line
var socket = require("socket.io")(3000, { pingTimeout: 63000, });
and try adding this in io variable
var io = require("socket.io")(server, {pingTimeout: 63000, });
I'm working on small app using node.js and basic html/js web page.
On localhost, I have no problem, webSocket works as well, but when I try on my dedicated server (ovh/kimsufi server), my websocket client return timeout error :
On my server :
ws.js :
var http = require('http'),
WebSocket = require('ws'),
WebSocketServer = WebSocket.Server;
var server = http.createServer();
server.listen('3005', '0.0.0.0', function() {
console.log('Listening on ' + server.address().address + ':' + server.address().port);
var wss = new WebSocketServer({server: server});
wss.on('connection', function(client){
console.log('connected');
client.on('message', function(message) {
client.send('received');
console.log(data);
});
});
});
Result on Linux console :
-----#-----:~/---/---/nodeServer$ node ws.js Listening on 0.0.0.0:3005
On my client :
var p1 = new Promise(function(resolve, reject) {
ws = new WebSocket("ws://------.---:3005");
});
Result in chrome/firefox console :
comm.js:12 WebSocket connection to 'ws://------.---:3005/' failed:
Error in connection establishment: net::ERR_CONNECTION_TIMED_OUT
I think this error apears when I did a new virtualHost, can it block the websocket ?
I believe this is a simple question: I have a websocket server (index.js) that opens a serial port when the browser (index.html) is loaded. I have a scale connected via USB (COM3). From the browser I want to send commands to the scale and receive data back to the browser. My node version is v7.7.4 and npm version is 4.1.2. I have also NPM installed serialport and ws.
index.js
var SerialPort = require('serialport');// include the library
//var SerialPort = serialport.SerialPort; // make a local instance of it
var WebSocketServer = require('ws').Server;
var SERVER_PORT = 8080; // port number for the webSocket server
var wss = new WebSocketServer({port: SERVER_PORT}); // the webSocket server
var connections = new Array; // list of connections to the server
wss.on('connection', handleConnection);
// get port name from the command line:
portName = process.argv[2];
var myPort = new SerialPort(portName, {
baudRate: 9600,
// look for return and newline at the end of each data packet:
parser: SerialPort.parsers.readline("\n")
});
myPort.on('open', showPortOpen);
myPort.on('data', sendSerialData);
myPort.on('close', showPortClose);
myPort.on('error', showError);
// This function broadcasts messages to all webSocket clients
function broadcast(data) {
for (myConnection in connections) { // iterate over the array of connections
connections[myConnection].send(data); // send the data to each connection
}
}
function sendToSerial(data) {
myPort.write(" From: index.js:sendToSerial "+data);
console.log("sendToSerial (index.js): " + data);
// if there are webSocket connections, send the serial data
// to all of them:
if (connections.length > 0) {
broadcast(data);
}}
function handleConnection(client) {
console.log("New Connection"); // you have a new client
connections.push(client); // add this client to the connections array
client.on('message', sendToSerial); // when a client sends a message,
client.on('close', function() { // when a client closes its connection
console.log("connection closed"); // print it out
var position = connections.indexOf(client); // get the client's position in the array
connections.splice(position, 1); // and delete it from the array
});
}
function showPortOpen() {
console.log(portName+' port open. Data rate: ' + myPort.options.baudRate);
}
function sendSerialData(data) {
myPort.write(" From: index.js:sendSerialData "+data);
myPort.write("sendSerialData "+data);
console.log("sendSerialData "+data);
}
function showPortClose() {
console.log('port closed.');
}
function showError(error) {
console.log('Serial port error: ' + error);
}
and index.html
<!DOCTYPE html>
<html>
<head>
<script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/p5.js/0.4.8/p5.min.js"></script>
<script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/p5.js/0.4.8/addons/p5.dom.js"></script>
<script type="text/javascript">
var text; // variable for the text div you'll create
var socket = new WebSocket("ws://localhost:8080");
function setup() {
// The socket connection needs two event listeners:
socket.onopen = openSocket;
socket.onmessage = showData;
// make a new div and position it at 10, 10:
text = createDiv("xxSensor reading:");
text.position(10,10);
}
function openSocket() {
text.html("Socket open");
socket.send("Hello websocket server - from index.html");
}
function showData(result) {
// when the server returns, show the result in the div:
text.html("Sensor reading: " + result.data);
xPos = int(result.data); // convert result to an integer
text.position(xPos, 10); // position the text
}
I have tried SERVER_PORT = 8081 with the same results.
I am able to see info from index.html in the cmd "node index.js COM3" but the command myPort.write does not get to the index.html browser.
I get:
C:\Users\pmfoo\nodeSerialExample>node index.js COM3
COM3 port open. Data rate: 9600
New Connection
sendToSerial (index.js): Hello websocket server - from index.html
sendSerialData 277.5 g
sendSerialData
where 277.5 g is the output from the scale on COM3.
and in the browser:
Sensor reading: Hello websocket server - from index.html
I followed Tom Igoe's tutorial https://itp.nyu.edu/physcomp/labs/labs-serial-communication/lab-serial-communication-with-node-js/ with only partial results. I cannot write from index.js to index.html nor can I send a command via index.js to the scale. This scale command ("ON" or "OFF" or "PSN") is seen by index.js. Can anyone help me solve these 2 communication problems?
I am new to Nodejs and am trying to set up a server client connection using sockets. Below is my code. Server is working OK but client is not connecting.
Please can anyone help me figure out the mistake.
Much Thanks
jessi
Server.js
var express = require('express');
var app = express();
var server = require('http').createServer(app);
var io = require('socket.io')(server);
io.on('connection', function(socket){
console.log('a user connected');
socket.on('disconnect', function(){
console.log('user disconnected');
});
});
io.on('data', function(data) {
console.log('DATA from client is: ' + data);
// Close the client socket completely
});
server.listen(4200);
console.log('Monitoring server listening on port 4200');
Client.js
var HOST = '127.0.0.1';
var PORT = 4200;
var express = require('express');
var app = express();
var client = require('http').createServer(app);
var io = require('socket.io')(client);
client.connect(PORT, HOST, function()
{
console.log('CONNECTED TO: ' + HOST + ':' + PORT);
// Write a message to the socket as soon as the client is connected,
// the server will receive it as message from the client
io.write('I am Chuck Norris!');
});
// Add a 'data' event handler for the client socket
// data is what the server sent to this socket
client.on('data', function(data) {
console.log('DATA: ' + data);
// Close the client socket completely
client.destroy();
});
// Add a 'close' event handler for the client socket
client.on('close', function() {
console.log('Connection closed');
});
For the client you use the socket.io-client package instead. The client side doesn't require the use of the Express portion since you're not recreating a web server on the client. If you look at your current code you're essentially recreating the Socket server which isn't what you want to do.
All that is necessary is to create a new Socket.io client and register your various event handlers.
var socket = require('socket.io-client')('localhost:4200');
socket.on('data', function(data) {
// handle incoming data
console.log(data);
});
I'm new with node.js/express and all and I want to be able to notify any clients in browser about a new message received from some algorithm in the back-end. The publisher algorithm connect to the websocket and writes the message.
As far as I've looked there were examples which recommended websockets but I haven't been able to run that code in browser only in console.
Example client code:
var WebSocket = require('faye-websocket');
var ws = new WebSocket.Client('ws://localhost:1234');
var http = require('http');
var port = process.env.PORT || 1235;
var server = http.createServer()
.listen(port);
// receive a message from the server
ws.on('message', function(event) {
alert(JSON.parse(event.data));
});
Thank you
Found the answer after some trial/error iterations.
The algorithm now does a POST to an URL which in turn triggers a write to sockets for all connected clients via socket.io.
Client code:
var socket = io('http://localhost:7777');
socket.on('message', function (msg) {
document.body.insertAdjacentHTML( 'beforeend', '<div id="myID">'+msg+'</div>' );
});
And on the server, when client connects I retain it's socket into an array so I can write to each one:
Server code:
io.on('connection', function(socket){
console.log('a user connected: '+socket.id);
var id = clientCount++;
clientSockets[id] = socket;
socket.on('disconnect', function(){
console.log('user disconnected');
delete clientSockets[id];
socket = null
});
});
app.post('/alerts', function(req, res) {
req.accepts(['json', 'application']);
console.log("Algo did a POST on /alerts!");
// send the message to all clients
//console.log(req.body);
for(var i in clientSockets) {
clientSockets[i].send(JSON.stringify(req.body));
}
res.send(200);
});
In conclusion, I'm not using faye-websockets but instead socket.io