im trying to connect my client through web sockets in JS but I have this error
getUser.js:29 WebSocket connection to 'ws://localhost:8005/wsserver.js' failed: Connection closed before receiving a handshake response
But look my code:
getUser.js
var sock = new WebSocket("ws://localhost:8005/wsserver.js");
$('#data1').append("alors");
sock.onopen = function (event) {
$('#data').append("server status opened" + event.currentTarget.URL);
sock.send(JSON.stringify("coucou"));
console.log("sended");
};
sock.onmessage = function (event) {
$('#data').append(event.data);
console.log(event.data);
};
sock.onerror = function(error) {
console.log('WebSocket Error: ' + error);
};
And the server side code is:
wsserver.js
var WebSocketServer = require("ws").Server;
var ws = new WebSocketServer( { port: 8005 } );
console.log("Server started...");
ws.on('connection', function (ws) {
console.log("Browser connected online...")
ws.on("message", function (str) {
var ob = JSON.parse(str);
switch(ob.type) {
case 'text':
console.log("Received: " + ob.content)
ws.send('{ "type":"text", "content":"Server ready."}')
break;
case 'image':
console.log("Received: " + ob.content)
console.log("Here is an apricot...")
var path ="apricot.jpg";
var data = '{ "type":"image", "path":"' + path + '"}';
ws.send(data);
break;
}
})
ws.on("close", function() {
console.log("Browser gone.")
})
});
But the error is still here, i don't understand why
Take script part away from your client:
var sock = new WebSocket("ws://localhost:8005");
Server app is running in that port and all you need is to connect to the port.
Related
I am trying to get a client to speak with a server and am unable to receive the events being emitted by the client. The connection is being established as the server console.logs connected to localhost:61201 whenever a client connects; but, there is no response from the clientEvents that are being emitted at intervals by the client.
server.js
const port = 61201;
const ipAddress = "127.0.0.1"
var http = require('http');
var io = require('socket.io');
var server = http.createServer();
server.listen(port, ipAddress);
var socket = io.listen(server);
socket.on('connect', () => {
console.log('connected to localhost:61201');
socket.on('clientEvent', function (data) {
console.log('message from the client:', data);
socket.emit('serverEvent', "thanks server! for sending '" + data + "'");
});
});
client.js
const port = 61201;
const ipAddress = "127.0.0.1";
const url = 'http://' + ipAddress + ':' + port;
var io = require('socket.io-client');
var socket = io(url);
socket.on('connect', () => {
socket.on('serverEvent', function (data) {
console.log('new message from the server:', data);
});
setInterval(function () {
socket.emit('clientEvent', Math.random());
console.log('message sent from the client');
}, 3000);
});
You need to use the socket object that the connect event returns. Try this
socket.on('connect', (clientSocket) => {
console.log('connected to localhost:61201');
clientSocket.on('clientEvent', function (data) {
console.log('message from the client:', data);
clientSocket.emit('serverEvent', "thanks server! for sending '" + data + "'");
});
});
I have created one socket server in node js where I can send some data and receive from the server, but the problem is every time connection is closing and creating new PID for another request. here my requirement is once my IOT device connects to the server then the connection should stay there and I want to send, receive data any time.
Can anyone help me out?
I am posting my code below
Server code
var net = require('net');
// Create Server instance
var server = net.createServer(main);
server.listen(9010, function() {
console.log('server listening on %j', server.address());
});
function main(sock) {
sock.setEncoding("utf8");
sock.on('data', function(data) {
var data = data;
console.log('Request data is ', data);
console.log('Says:', data);
sock.write("responding to client");
sock.write(' exit');
});
sock.on('close', function () {
console.log('connection closed');
});
sock.on('error', function (err) {
console.log('Connection error: %s', err.message);
});
};
Client code
var net = require('net');
//params
var HOST = 'myhost';
var PORT = 9010;
var client = new net.Socket();
client.connect(PORT, HOST, function() {
console.log('CONNECTED TO: ' + HOST + ':' + PORT);
client.write('Hello socket server');
});
client.on('data', function(data) {
console.log('Recieved data: ' + data);
client.destroy();
});
// Add a 'close' event handler for the client socket
client.on('close', function() {
console.log('Connection closed');
});
I have 2 clients, I need client1 gives information to client2 and this receive an alert of it, I'm implementing Websocket "ws" with NodeJS for this.
Client1 web page receive an answer via AJAX and send information to server.js in JSON format, like this example:
/mysite_folder/client1/client1.php
<script>
var userorder = $("#user").val(); //client2 username who will receive information
$.post("myscript.php",{
my: variables
}).done(function(response){
var wsUri = "wss://www.mysite.com:3000/sockets/";
var output;
websocket = new WebSocket(wsUri);
websocket.onopen = onOpen;
websocket.onclose = onClose;
websocket.onmessage = onMessage;
websocket.onerror = onError;
function onOpen(evt){
output = {
"status": "ASSIGNED",
"user": userorder
};
doSend(JSON.stringify(output));
}
function doSend(message){
websocket.send(message);
websocket.close();
}
function onMessage(evt){
}
function onClose(evt){
location.reload();
}
function onError(evt){
}
});
</script>
After client1 send information, connection closes and refresh client1 page. My server receives this JSON information like this: /mysite_folder/sockets/server.js
var WebSocketServer = require('ws').Server,
fs = require('fs');
var cfg = {
ssl: true,
port: 3000,
ssl_key: '/path/of/sslkey',
ssl_cert: '/path/of/sslcert'
};
var httpServ = ( cfg.ssl ) ? require('https') : require('http');
var app = null;
var processRequest = function( req, res ) {
res.writeHead(200);
res.end("All glory to WebSockets!\n");
};
if ( cfg.ssl ) {
app = httpServ.createServer({
// providing server with SSL key/cert
key: fs.readFileSync( cfg.ssl_key ),
cert: fs.readFileSync( cfg.ssl_cert )
}, processRequest ).listen( cfg.port );
} else {
app = httpServ.createServer( processRequest ).listen( cfg.port );
}
var wss = new WebSocketServer( { server: app } );
wss.on('connection', function connection(ws){
console.log("User connected");
ws.on('message', function incoming(message){
var info = JSON.parse(message); //receive client1 info
if(info.status=="ASSIGNED"){
ws.send(info.user); //send client2 username
}
});
});
Parsing JSON and comparing that information status is "ASSIGNED" I need "info.user" send to client2 page displaying an alert message, so in client2 I wrote like this example: /mysite_folder/client2/client2.php
$(document).ready(function(){
var user = $("#user").val(); //client2 username
var wsUri = "wss://www.mysite.com:3000/sockets/";
var output;
websocket = new WebSocket(wsUri);
websocket.onopen = onOpen;
websocket.onclose = onClose;
websocket.onmessage = onMessage;
websocket.onerror = onError;
function onOpen(evt){
}
function doSend(message){
}
function onMessage(evt){
if(user==evt){ //if client2 username sent by server is the same with client2 username logged in the page, make an alert
alert("Your order was ASSIGNED");
}
websocket.close();
}
function onClose(evt){
}
function onError(evt){
}
});
Connections works fine, client1 is working well, but in client2 doesn't happen anything, how can I make client2 get this alert?
UPDATE
On server.js I added a broadcast method like this:
var wss = new WebSocketServer( { server: app } );
// Broadcast to all.
wss.broadcast = function broadcast(data) {
wss.clients.forEach(function each(client) {
if ( client.readyState == WebSocketServer.OPEN) {
client.send(data);
}
});
};
wss.on('connection', function connection(ws){
console.log("User connected");
ws.on('message', function incoming(message){
//Broadcast to everyone else
var info = JSON.parse(message);
console.log(info.user); //shows username in console
wss.clients.forEach(function each(client) {
if (client !== ws && client.readyState === WebSocketServer.OPEN) {
if(info.status=="ASSIGNED"){
client.send(info.user);
}
}
});
});
});
But client2 is still doesn't receiving message from server and not displaying the alert.
I would like some help.
The issue is your sending data back down the same socket connection you receive the message i.e. ws.send(info.user), ws refers to that client connection only.
The server has a broadcast method you can use which sends the message to all active connections
wss.broadcast(info.user);
I have the simple node.js server that receives udp packages and prints them in the console:
var PORT = 19777;
var MULTICAST_GROUP = "224.0.0.251";
var dgram = require("dgram");
var payload = new Buffer('A wild message appears');
var client = dgram.createSocket("udp4");
client.on("message", function(message, rinfo) {
console.log("received: ",message);
});
client.on("listening", function() {
console.log("listening on ",client.address());
client.setBroadcast(true);
client.setTTL(64);
client.setMulticastTTL(64);
client.setMulticastLoopback(true);
client.addMembership(MULTICAST_GROUP);
client.send(payload, 0, payload.length, PORT, MULTICAST_GROUP, function(err,bytes) {
console.log("err: "+err+" bytes: "+bytes);
// client.close();
});
});
client.on("close", function() {
console.log("closed");
});
client.on("error", function(err) {
console.log("error: ",err);
});
client.bind(19777);
it works remotely on my server. I want to present the received data to each client that will turn on his browser and enter the address of my server. How could I do that?
I'm trying to make websokects work with node.js using express and websocket modules.
The funny thing is that if I use the http module to create the server they work as expected, I receive status 101.
But if I use the express module to create the server it'll throw an error:
WebSocket connection to 'ws://localhost:2345/' failed: Error in connection establishment: net::ERR_CONNECTION_REFUSED
Here's the code
// using http module (works)
var WebSocketServer = require("websocket").server;
var http = require("http");
var app = http.createServer(function(request, response) {
response.writeHeader(200, {'Content-Type':'text/html'});
response.end(""+
"<!DOCTYPE html>"+
"<html>"+
"<head>"+
"<script>"+
"var ws = new WebSocket('ws://localhost:2345/');"+
"ws.onmessage = function(event) { "+
"var span = document.createElement('span');"+
"span.innerHTML = event.data;"+
"document.body.appendChild(span);"+
"}"+
"</script>"+
"</head>"+
"<body>"+
"<span>Messages: </span>"+
"</body>"+
"</html>"
);
});
app.listen(2345);
wsServer = new WebSocketServer({'httpServer':app});
wsServer.on("request", function(request) {
var connection = request.accept(null, request.origin);
console.log("Connection ACCEPTED\n");
connection.on("message", function(message)
{
if(message.type == 'utf8')
{
console.log("Received Message: %s", message.utf8Data);
connection.sendUTF(message.utf8Data);
}
})
connection.on("close", function(reasonCode, description)
{
console.log("Connection lost\n");
})
})
and the non working part
// using express module (get error)
var WebSocketServer = require("websocket").server;
var app = require('express')();
var app.get('/', function(request, response) {
response.writeHeader(200, {'Content-Type':'text/html'});
response.end(""+
"<!DOCTYPE html>"+
"<html>"+
"<head>"+
"<script>"+
"var ws = new WebSocket('ws://localhost:2345/');"+
"ws.onmessage = function(event) { "+
"var span = document.createElement('span');"+
"span.innerHTML = event.data;"+
"document.body.appendChild(span);"+
"}"+
"</script>"+
"</head>"+
"<body>"+
"<span>Messages: </span>"+
"</body>"+
"</html>"
);
});
app.listen(2345);
wsServer = new WebSocketServer({'httpServer':app});
wsServer.on("request", function(request) {
var connection = request.accept(null, request.origin);
console.log("Connection ACCEPTED\n");
connection.on("message", function(message)
{
if(message.type == 'utf8')
{
console.log("Received Message: %s", message.utf8Data);
connection.sendUTF(message.utf8Data);
}
})
connection.on("close", function(reasonCode, description)
{
console.log("Connection lost\n");
})
})
What could be wrong there? How to solve this issue?
The app in Express is not the httpServer, so if the WebSocketServer doesn't explicitly know about Express and how to get the server from it, then you probably need to give it the actual httpServer object rather than the Express object which you can do by changing this:
app.listen(2345);
wsServer = new WebSocketServer({'httpServer':app});
to this:
var server = app.listen(2345);
var wsServer = new WebSocketServer({'httpServer': server});