My angularjs client websocketserver can properly send to the server, but when sending from server to client, the client doesn't register the event.
I'm using angular-websockets at the client side and ws at my express.js server
Here's my code.
server
var port = process.env.PORT || 3002;
var server = http.createServer(app); // app = express
server.listen(port);
var socketComs = require('./lib/socketcoms').connect(server);
var connect = function(server) {
var wss = new WebSocketServer({
server: server
});
wss.on('connection', function(ws) {
console.log("websocket connection open");
ws.on('message', function incoming(message) {
console.log('received', message); // THIS WORKS FINE
});
var id = setInterval(function() {
ws.send('pong', 'data 123', function(err) {
console.log('sent pong', err); // THIS IS NEVER CAUGHT BY CLIENT, err = clean
});
}, 2000); // Pong is never received
});
};
client
var connect = function() {
ws.$on('$open', function() {
console.log('wow its working');
ws.$emit('message', 'some message');
});
ws.$on('pong', function(data) {
console.log('yes', data);
});
ws.$on('$close', function(data) {
console.log('wss closed');
});
};
Can anyone see what's going wrong?
I'm using ng-websocket with PHP socket, and I have the same issue.
I just opened the ng-websocket.js and..guess what? the "ping" and "pong" events don't exist!
The "incoming" event is called "$message"...
This is how to get data from server:
ws.$on('$message', function (response) {
console.log("DATA FROM SERVER", response);
Related
I'm trying to make a connection between a react client and an express server with websockets. Every time I try this i get an error. I think I'm missing something.
Server code:
var http = require('http');
var ws = require('ws');
var theHttpServer = http.createServer();
var theWebSocketServer = new ws.Server({
server: theHttpServer,
verifyClient: true
});
theHttpServer.on('request', app);
theHttpServer.listen(9000,
function () {
console.log("The Server is lisening on port 9000.")
});
theWebSocketServer.on('connection', function connection(msg) {
console.log("CONNECTION CREATED");
websocket.on('message', function incoming(message) {
});
});
Client code:
let wsConnection = new WebSocket("ws://localhost:9000");
wsConnection.onopen = function(eventInfo) {
console.log("Socket connection is open!");
}
The error:
if (!this.options.verifyClient(info)) return abortHandshake(socket, 401);
^
TypeError: this.options.verifyClient is not a function
You're passing verifyClient as a boolean, not a function. What you would maybe want to do is change this to:
function verifyClient(info) {
// ...Insert your validation code here
};
var theWebSocketServer = new ws.Server({
server: theHttpServer,
verifyClient: verifyClient
});
Assuming that web sockets based on TCP I have created a simple TCP client, but I cannot get any response from echo.websocket.org. What am I doing wrong?
const connectionData: any = {
protocol: 'ws:',
host: 'echo.websocket.org',
port: '80'
}
var client = new net.Socket();
client.connect(connectionData, function () {
console.log('Connected');
client.write('Reply this.');
});
client.on('data', function (data) {
console.log('Received: ' + data);
});
client.on('close', function () {
console.log('Connection closed');
});
I try to make an application that receives from a third part application UDP packets.
I try to create a server UDP in NodeJS, but now when I receive the data I don't know how can I show it in a browser windows.
I explain better...my application receives data via udp in real time, the server processes them and should show them real time on a web page.
This is my code for UDP server in NodeJS:
const dgram = require('dgram');
const server = dgram.createSocket('udp4');
server.on('error', (err) => {
console.log(`server error:\n${err.stack}`);
server.close();
});
server.on('message', (msg, rinfo) => {
console.log(`server got: ${msg} from ${rinfo.address}:${rinfo.port}`);
console.log(` messaggio ricevuto ${msg}`);
});
server.on('listening', () => {
const address = server.address();
console.log(`server listening ${address.address}:${address.port}`);
});
server.bind({
adress:'127.0.0.1',
port:'41234'
});
// server listening address :41234
Thanks a lot for the reply
welcome to SO!
You could do something like below...
// Open a connection
var socket = new WebSocket('ws://localhost:41234/');
// When a connection is made
socket.onopen = function() {
console.log('Opened connection 🎉');
// send data to the server
var json = JSON.stringify({ message: 'Hello 👋' });
socket.send(json);
}
// When data is received
socket.onmessage = function(event) {
console.log(event.data);
}
// A connection could not be made
socket.onerror = function(event) {
console.log(event);
}
// A connection was closed
socket.onclose = function(code, reason) {
console.log(code, reason);
}
// Close the connection when the window is closed
window.addEventListener('beforeunload', function() {
socket.close();
});
This link should give you more info : https://www.sitepoint.com/real-time-apps-websockets-server-sent-events/ (above snippet is taken from this link)
You need a web server to send data to browser.
This link https://socket.io/get-started/chat will help you create a webserver.
You could send the message received on UDP port to the websocket as below
server.on('message', (msg, rinfo) => {
socket.emit('sendData', msg);
});
I'm a newbie working with an application with MEAN stack. It is an IoT based application and using nodejs as a backend.
I have a scenario in which I have to send a broadcast to each connected clients which can only open the Socket and can wait for any incoming data. unless like a web-browser they can not perform any event and till now I have already gone through the Socket.IO and Express.IO but couldn't find anything which can be helpful to achieve what I want send raw data to open socket connections'
Is there any other Node module to achieve this. ?
Here is the code using WebSocketServer,
const express = require('express');
const http = require('http');
const url = require('url');
const WebSocket = require('ws');
const app = express();
app.use(function (req, res) {
res.send({ msg: "hello" });
});
const server = http.createServer(app);
const wss = new WebSocket.Server({ server });
wss.on('connection', function connection(ws) {
ws.on('message', function(message) {
wss.broadcast(message);
}
}
wss.broadcast = function broadcast(msg) {
console.log(msg);
wss.clients.forEach(function each(client) {
client.send(msg);
});
};
server.listen(8080, function listening() {
console.log('Listening on %d', server.address().port);
});
Now, my query is when this code will be executed,
wss.on('connection', function connection(ws) {
ws.on('message', function(message) {
wss.broadcast(message);
}
}
var WebSocketServer = require("ws").Server;
var wss = new WebSocketServer({port:8100});
wss.on('connection', function connection(ws) {
ws.on('message', function(message) {
wss.broadcast(message);
}
}
wss.broadcast = function broadcast(msg) {
console.log(msg);
wss.clients.forEach(function each(client) {
client.send(msg);
});
};
Try the following code to broadcast message from server to every client.
wss.clients.forEach(function(client) {
client.send(data.toString());
});
Demo server code,
const WebSocket = require('ws')
const wss = new WebSocket.Server({ port: 2055 },()=>{
console.log('server started')
})
wss.on('connection', (ws) => {
ws.on('message', (data) => {
console.log('data received \n '+ data)
wss.clients.forEach(function(client) {
client.send(data.toString());
});
})
})
wss.on('listening',()=>{
console.log('listening on 2055')
})
I have a Express, Node and Socket.io application, when I inspect Network, I can see Socket is falling back to XHR reuqests rather than WebSockets.
Am I missing something obvious?
In my console I see, in my Networks tab I see no WebSocket, just XHR requests to socket.io:
WebSocket connection to 'ws://localhost/socket.io/?EIO=3&transport=websocket&sid=lVFuwHcH-XPm8zHhAAAA' failed: Error in connection establishment: net::ERR_SOCKS_CONNECTION_FAILED
Server Code:
var app = express(),
http = require('http').Server(app),
io = require('socket.io')(http),
io.on("connection", function (socket) {
var interval = setInterval(function () {
if(nt == ""){
socket.emit("message", {"data": "<strong>Waiting for data...</strong>"});
}else{
socket.emit("data", {
"mediumLoadTime": nt.mediumPageLoad(),
"firstLoadTime": nt.times[0],
"lastLoadTime": nt.times[nt.times.length-1],
//"times": nt.times,
"requests": nt.reqMade.toString(),
"success": nt.successful.toString(),
"error": nt.error.toString(),
"virtualusers": nt.virtualUsers.toString(),
"host": nt.options.host.toString(),
});
}
}, 10);
socket.on("disconnect", function () {
clearInterval(interval);
});
});
Client:
var socket = io();
socket.on('data', function (data) {
console.log(data);
});
In my view I require <script src="https://cdn.socket.io/socket.io-1.2.0.js"></script>