WS nodejs websockets how to make a the receiving client - node.js

Hello I am trying to learn how to connect a server to a website page. I have made my server in node.js and attempted to use the ws library. I'm not sure what to do on the client side. On the documentation page on ws (https://www.npmjs.com/package/ws#simple-server) it says I have to use "require" to import ws, however i'm assuming that you need to use node.js to use a "require" statement which I am not on my client.
Any tips or links to information is appreciated
// Server
const fs = require('fs');
const https = require('https');
const WebSocket = require('ws');
const path = require('path');
const server = https.createServer({
cert: fs.readFileSync(path.join(__dirname, 'cert', 'cert.pem')),
key: fs.readFileSync(path.join(__dirname, 'cert', 'key.pem'))
});
const wss = new WebSocket.Server({server})
console.log(server)
wss.on('connection', function connection(ws) {
ws.on('message', function incoming(message) {
console.log('received: %s', message);
});
ws.send('something');
});
server.listen(443, function () {
console.log('Server is listening on 443');
});
// html page --------------------------------------------------------------------------------
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
</head>
<body>
<script>
const ws = new WebSocket("wss://websiteName.com");
ws.on('open', function open() {
ws.send('something');
});
ws.on('message', function incoming(data) {
console.log(data);
});
</script>
</body>
</html>

Related

An alert can be accepted when loading page with selenium on internet explorer?

I'm trying to get an url with selenium and node.js, but when the site has an alert I can't accept it on Internet Explorer.
index.js
require('iedriver');
const express = require('express');
const webdriver = require('selenium-webdriver');
let ie = require('selenium-webdriver/ie');
function start(params) {
start_server();
let options = new ie.Options();     
options.ignoreZoomSetting(true);
let driver = new webdriver.Builder()
.forBrowser('internet explorer')
.withCapabilities(options)
.build();
let site="http://127.0.0.1:3000/";
driver.get(site)
.then(()=>{
return driver.wait(webdriver.until.alertIsPresent(),10000)
.then(()=>{
let alert = driver.switchTo().alert();
return alert.accept()
console.log("go on");
})
})
;
}
const start_server=()=>{
const app = express();
const PORT = 3000;
app.use(express.static('static'));
app.get('/', function(req, res){
let options = {
root: path.join(__dirname+"/../static/")
};
let fileName = 'index.html';
res.sendFile(fileName, options, function (err) {
if (err) {
log(err);
} else {
console.log('Sent:', fileName);
}
});
});
app.listen(PORT, function(err){
if (err) console.log(err);
console.log("Server listening on PORT", PORT);
});
};
start();
The site to open has an alert when page is loading, like this:
index.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<script src="loading.js"></script>
<title>Document</title>
</head>
<body>
</body>
</html>
loading.js
alert("accept before start");
This has to work on Internet Explorer.
When running , after 5 minutes it shows this
UnhandledPromiseRejectionWarning: TimeoutError: Timed out waiting for page to load.
at Object.throwDecodedError (C:\d\adhoc\node\copyimgwz\node_modules\selenium-webdriver\lib\error.js:517:15)
at parseHttpResponse (C:\d\adhoc\node\copyimgwz\node_modules\selenium-webdriver\lib\http.js:642:13)
and stops like this
blocking alert on ie with selenium
Please, any idea how to accept that alert with selenium?
EDIT
I found out a solution, adding this line it's already working fine
options.introduceFlakinessByIgnoringProtectedModeSettings(true);
I was able to make it work, adding this line
options.introduceFlakinessByIgnoringProtectedModeSettings(true);
in this section
let options = new ie.Options();
options.ignoreZoomSetting(true);
options.introduceFlakinessByIgnoringProtectedModeSettings(true);
Aparently, On internet explorer you need to activate this characteristic to let you work.

socket.io send data from server to client

I am trying to send some json object from the server side to the client side.
var express = require('express');
var app = express();
var server = app.listen(1337);
var io = require('socket.io').listen(server);
var json = {
var1: 1,
var2: 2,
var3: 3,
};
io.on('connection', function(json) {
io.send('message', json);
});
app.listen(3000);
and on index.html
<!DOCTYPE html>
<html>
<head></head>
<body>
<script src="https://cdn.socket.io/socket.io-1.0.0.js"></script>
<script>
var socket = io.connect('http://localhost:3000');
socket.on('message', function(data) {
console.log(data);
});
</script>
</body>
</html>
I keep getting this error
Access to XMLHttpRequest at 'http://localhost:3000/socket.io/?
EIO=2&transport=polling&t=1602487581123-0' from origin 'null' has been blocked by CORS policy: No
'Access-Control-Allow-Origin' header is present on the requested resource.
Use "socket.io": "^2.3.0", for server side, change server side code to following:
var express = require('express');
var app = express();
var http = require('http').createServer(app);
var io = require('socket.io')(http);
var json = {
var1: 1,
var2: 2,
var3: 3,
};
io.on('connection', function() {
io.send('message', json);
});
http.listen(3000, () => console.log('HTTP server is listening on port 3000'));
For the CORS header, any origins being allowed by default.
And I recommend you use the latest version of socket.io for the client-side. You can use this CDN.
client side:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
</head>
<body>
<script src="https://cdnjs.cloudflare.com/ajax/libs/socket.io/2.3.1/socket.io.js" integrity="sha512-AcZyhRP/tbAEsXCCGlziPun5iFvcSUpEz2jKkx0blkYKbxU81F+iq8FURwPn1sYFeksJ+sDDrI5XujsqSobWdQ==" crossorigin="anonymous"></script>
<script>
var socket = io.connect('http://localhost:3000');
socket.on('message', function(data, json) {
console.log(data, json);
});
</script>
</body>
</html>
Create HTTP Server for client-side:
☁ 64313396 [master] ⚡ http-server -p 3001
Starting up http-server, serving ./public
Available on:
http://127.0.0.1:3001
http://172.31.160.227:3001
http://10.23.128.81:3001
The output of browser console:

Sending a WebSocket message from a POST request handler in express

I have an Express server that listens for webhook events from an external API. When it received these events, I want the handler for that http request to send a message to a WebSocket client. Here is some basic code to illustrate what I mean
The external API will send a HTTP POST request to an endpoint on my Express server, lets say it looks like this:
app.post('/external-api', (req, res) => {
// webhook payload will be in req.body
})
In that handler for /external-api I'd like to send a message to a client who's connected to the server via WebSocket. As of right now, I'm using the npm ws library, so I want the logic to look something like this
app.post('/external-api', (req, res) => {
ws.broadcast(req.body);
})
Is there a way to do this? I'm open to using other libraries but I just need a way to send a message to a WebSocket client from a HTTP POST request handler in Express.
Here is an example:
index.ts:
import express from 'express';
import WebSocket from 'ws';
import http from 'http';
import path from 'path';
import faker from 'faker';
const app = express();
const port = 3000;
const server = http.createServer(app);
const wss = new WebSocket.Server({ server });
wss.on('connection', (ws: WebSocket) => {
console.log('establish websocket connection');
ws.on('message', (message) => {
console.log('received: %s', message);
});
});
app.get('/client/:id', (req, res) => {
res.sendFile(path.resolve(__dirname, `./public/client-${req.params.id}.html`));
});
app.get('/external-api', (req, res) => {
wss.clients.forEach((client) => {
if (client.readyState === WebSocket.OPEN) {
client.send(faker.internet.email());
}
});
res.sendStatus(200);
});
server.listen(port, () => console.log(`http server is listening on http://localhost:${port}`));
client-1.html:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>client 1</title>
</head>
<body>
<p>client 1</p>
<button id="test">Test</button>
<script>
(function() {
window.onload = function() {
const socket = new WebSocket('ws://localhost:3000');
// Connection opened
socket.addEventListener('open', function(event) {
socket.send('Hello Server! Client - 1');
});
// Listen for messages
socket.addEventListener('message', function(event) {
console.log('Message from server ', event.data);
});
const btn = document.getElementById('test');
btn.addEventListener('click', async () => {
try {
const res = await fetch('http://localhost:3000/external-api');
console.log(res);
} catch (error) {
console.log(error);
}
});
};
})();
</script>
</body>
</html>
client-2.html:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>client 2</title>
</head>
<body>
<p>client 2</p>
<button id="test">Test</button>
<script>
(function() {
window.onload = function() {
const socket = new WebSocket('ws://localhost:3000');
// Connection opened
socket.addEventListener('open', function(event) {
socket.send('Hello Server! Client - 2');
});
// Listen for messages
socket.addEventListener('message', function(event) {
console.log('Message from server ', event.data);
});
const btn = document.getElementById('test');
btn.addEventListener('click', async () => {
try {
const res = await fetch('http://localhost:3000/external-api');
console.log(res);
} catch (error) {
console.log(error);
}
});
};
})();
</script>
</body>
</html>
Now, click the button of client 1, send HTTP request to /external-api.
The console logs of client 1:
The console logs of client 2:
The logs of server:
http server is listening on http://localhost:3000
establish websocket connection
received: Hello Server! Client - 1
establish websocket connection
received: Hello Server! Client - 2
As you can see, the server broadcast fake emails to client 1 and client 2.

Sends get request from node to web service

I have a web service and a node project with a html page. I want to sends get request from my node project to my web service and in the return of web service i want to print that "hello world" on my website.
My web service.
import javax.ws.rs.GET;
import javax.ws.rs.Path;
import javax.ws.rs.Produces;
import javax.ws.rs.core.MediaType;
#Path("myresource")
public class MyResource {
#GET
#Produces(MediaType.TEXT_PLAIN)
public String hello() {
return "Hello World";
}
}
My Node project:
var express=require('express');
var http = require('http');
var https = require("https");
var request=require("request");
var app=express();
app.get('/',function(req,res){
res.sendfile('index.html');
});
app.listen(3000,function(){
console.log("Express Started on Port 3000");
});
app.get('/this',function(req,res){
request
.get('http://localhost:8080/ConnectingToNode/webapi/myresource')
.on('response', function(response) {
console.log(response.statusCode); // 200
console.log(response.headers['content-type']);
var a=response.toString();
console.log(a);
});
});
module.exports = app;
My index.html
<!DOCTYPE html>
<html>
<head>
<title>TO supply a title</title>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
</head>
<body>
<script>
function This(){
window.open("http://localhost:8080/ConnectingToNode/webapi/myresource");
}
</script>
<button onclick="This()" type="button">Click Me!</button>
</body>
</html>

node.js and socket.io

I have created a small server for communication using node.js and socket io
Server:
var express = require('/usr/local/lib/node_modules/express')
var io = require('/usr/local/lib/node_modules/socket.io');
var server = express.createServer();
server.listen(8888,'localhost');
io = io.listen(server);
io.of("namespace").on('connection', function(client){
client.emit("message",'connection successful');
client.on('message', function(m){
console.log("received message"+m);
client.broadcast(m);
});
});
Client:
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<title>Comet Test</title>
<script src="http://localhost:8888/socket.io/socket.io.js" type="text/javascript"></script>
</head>
<body>
<p><a id='customAlert' href="#" onclick='sendMessage("customAlert")'>publish customAlert</a></p>
<p><a id='customAlert2' href="#" onclick='sendMessage("customAlert2")'>publish customAl
<script type="text/javascript">
// Start the socket
var socket = io.connect('http://localhost:8888/namespace');
socket.on('error', function (reason){
console.error('Unable to connect Socket.IO', reason);
});
socket.on('message', function(msg){
console.log(msg);
});
function sendMessage(m) {
console.log("sending message"+m);
socket.emit("message",m);
}
</script>
</body>
Communication does not happen, am I doing something wrong here?
If your server is listening on port 8888, you need the client to connect to the server on port 8888.
The following line in your client code:
var socket = io.connect('http://localhost/namespace');
Should read:
var socket = io.connect('http://localhost:8888/namespace');

Resources