WebSocket connection to 'wss' failed - node.js

im trying to implement a chat client, i think my client server communication work, because i receive the messages in different tabs. im using a https connection
im getting in chrome following error:
WebSocket connection to 'wss://localhost/socket.io/?EIO=4&transport=websocket&sid=B-vRFkxNxHPkiK6cAAAE' failed: websocket.js:54
in firefox:
Firefox can’t establish a connection to the server at wss://localhost/socket.io/?EIO=4&transport=websocket&sid=vSwzZh9BE3cpHZHPAAAC.
im using a self signed certificate, that i created with openssl, thats why i get follwing konsole log in chrome:
This site does not have a valid SSL certificate! Without SSL, your site's and visitors' data is vulnerable to theft and tampering. Get a valid SSL certificate before releasing your website to the public.
server.js:
const express= require('express')
const app= express();
const https= require('https')
const fs=require('fs')
const PORT=process.env.PORT || 443
const httpsOptions={
key: fs.readFileSync('cert/key.pem'),
cert: fs.readFileSync('cert/cert.pem')
}
var server=https.createServer(httpsOptions,app);
server.listen(PORT,function(){
console.log(`listening to port ${PORT}`)
})
const io = require('socket.io')(server,{maxHttpBufferSize:1e8}).listen(server)
app.get('/test', (req,res)=>{
res.sendStatus(200);
})
app.use(express.static(__dirname + '/public'))
app.use(require('./routes/posts'));
app.use(require('./routes/users'));
//app.use(require('./public/client'));
app.get('/',(req,res)=>{
res.sendFile(__dirname + '/login_register/login.html')
})
app.get('/register',(req,res)=>{
res.sendFile(__dirname + '/login_register/register.html')
})
app.get('/chatroom',(req,res)=>{
res.sendFile(__dirname + '/index.html')
})
io.on('connection',(socket)=>{
console.log('new connection',socket.id)
socket.on('message', (msg)=>{
socket.broadcast.emit('message',msg)
})
socket.on('file-message', (msg)=>{
socket.broadcast.emit('file-message',msg)
})
})
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">
<title>Document</title>
<link rel="stylesheet" href="/style.css">
<script src="https://cdn.socket.io/4.4.1/socket.io.min.js" integrity="sha384-fKnu0iswBIqkjxrhQCTZ7qlLHOFEgNkRmK2vaO/LbTZSXdJfAu6ewRBdwHPhBo/H" crossorigin="anonymous"></script>
</head>
<body>
<section class="chat_section">
<div class="brand">
<img src="" alt="">
<h1> chat</h1>
</div>
<div class="message_area">
</div>
<div>
<textarea id="textarea" cols="30" rows="1" placeholder="write a message "></textarea>
</div>
<input type="file"id="fileupload" name="fileName">
<button id="submitFile" onclick="submitData()">senden</button>
</section>
<script>
socket = io('https://localhost:443/')
//also testet:
//const socket=io()
//didnt worked
let userName;
let userName_;
//const textarea = document.getElementById('textarea')
let textarea=document.querySelector('#textarea')
let messageArea= document.querySelector('.message_area')
let file__ = document.querySelector('#fileupload')
userName=sessionStorage.getItem('displayUsername')
userName_= userName
console.log(userName_)
sessionStorage.removeItem('displayUsername');
sessionStorage.clear();
//console.log(userName_)
if(userName_==null){
alert("dont scam")
window.location.href = '/'
}
//console.log(localStorage.getItem(displayUsername));
textarea.addEventListener('keyup', (e)=>{
if(e.key === 'Enter'){
sendMessage(e.target.value)
}
})
function sendMessage(message){
let msg= {
user:userName_,
message:message.trim()
}
//append message to frontend call function
appendMessage(msg,'outgoing')
textarea.value=""
scrollBottom()
//send to server
socket.emit('message', msg)
}
function appendMessage(msg,type,isFile){
//dont needed to understand
}
//recive messages
socket.on('message',(msg)=>{
//console.log(msg)
appendMessage(msg,'incoming')
scrollBottom()
})
socket.on('file-message',(msg)=>{
console.log(msg)
//File name Here
let message={
message: msg.filename,
user: msg.user,
result: msg.result
}
//send to the others
appendMessage(message,'incoming',isFile=true)
})
function scrollBottom(){
messageArea.scrollTop=messageArea.scrollHeight
}
function submitData(){
//dont needed to understand
}
}
function downloadFile(result,filename){
//dont needed to understand
}
</script>
</body>
</html>

Related

Android app does not connect via socket.io

Android app does not connect via socket.io, but via browser everything is fine. If I access via browser http://localhost:3000, it works, but when I run the android app nothing happens and there is no error message either. Note: I am using nodejs.
MainActivity.java
package com.security.myapplication;
import androidx.appcompat.app.AppCompatActivity;
import android.os.Bundle;
import java.net.URISyntaxException;
import io.socket.client.IO;
import io.socket.client.Socket;
public class MainActivity extends AppCompatActivity {
public Socket socket;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
//I created a ddns domain for external access directing to the nodejs
server port 3000
try {
socket = IO.socket("http://my_domain_ddns:3000");
socket.connect();
} catch (URISyntaxException e) {
e.printStackTrace();
}
}
}
node.js
const express = require('express');
const path = require('path');
const app = express();
const server = require('http').createServer(app);
const io = require('socket.io')(server);
app.use(express.static(path.join(__dirname, 'public')));
app.set('views', path.join(__dirname, 'public'));
app.engine('html', require('ejs').renderFile);
app.set('view engine', 'html');
app.use('/', (req, res) => {
res.render('index.html');
});
io.on('connection', socket => {
console.log(`Socket conectado: ${socket.id}`);
});
server.listen(3000);
index.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="with=device-with, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>Chat</title>
<script src="https://code.jquery.com/jquery-3.6.0.min.js" integrity="sha256-/xUj+3OJU5yExlq6GSYGSHk7tPXikynS7ogEvDej/m4=" crossorigin="anonymous"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/socket.io/3.1.3/socket.io.js"></script>
<link rel="stylesheet" href="styles.css">
</head>
<body>
<form id="chat">
<input type="text" name="username" placeholder="Digite seu usuario">
<div class="messages"></div>
<input type="text" name="message" placeholder="Digite sua mensagem">
<button type="submit">Enviar</button>
</form>
<!-- Fazendo a conexao do front com o socket -->
<script type="text/javascript">
var socket = io('http://my_domain_ddns:3000');
</script>
</body>
</html>
I have corrected the url in index.html
var socket = io('http://my_domain_ddns:3000');
Change localhost in your android by the public IP of your router.
Do a port forwarding from your router to your server.
Check that your server has the port where you do your forwarding is open.
This video video give more explanation.
Well, I found another way that worked.
private void initiateSocketConnection() {
OkHttpClient client = new OkHttpClient();
Request request = new Request.Builder().url(SERVER_PATH).build();
webSocket = client.newWebSocket(request, new SocketListener());
}
build.grade
implementation 'com.squareup.okhttp3:okhttp:3.10.0'

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.

node.js socke.io chat app : not sending message between two browser windows where is my mistake

js code. which is a server file
while i am running this below code it is not sending messages when i click the button.
var express = require('express');
var socket = require('socket.io');
var app = express();
var server = app.listen(8000,function(){
console.log("The server is listening on the port 8000");
});
app.use(express.static('public'));
var io = socket(server);
io.on('connection', function(socket){
socket.on("chat", function(data){
io.sockets.emit("chat", data);
});
});
here is my index.html code which also contains
and css file which i am not included here
<!DOCTYPE html>
<html>
<head>
<title>my first chat app</title>
<script
src="https://cdnjs.cloudflare.com/ajax/libs/socket.io/2.0.3/socket.io.js">
</script>
<link rel="stylesheet" type="text/css" href="style.css">
</head>
<body>
<div id="mario-chat">
<div id="chat-window">
<div id="output"></div>
<div id="feedback"></div>
</div>
<input id="handle" type="text" placeholder="Handle"/>
<input id="message" type="message" placeholder="Message"/>
<button id="send">Send</button>
</div>
<script src="/chat.js"></script>
</body>
</html>
the above code include a stylesheet.css file for looking good.
here is my chat.js file which is client side functionalities.
var socket = io.connect("http://localhost:8000");
var message = document.getElementById("message");
var handle = document.getElementById("handle");
var btn = document.getElementById("send");
var output = document.getElementById("output");
var feedback = document.getElementById("feedback");
btn.addEventListener("click",function(){
socket.emit("chat", {message:message.value,handle:handle.value});
});
socket.on("chat", function(data){
output.innerHTML += '<p><strong>' + data.handle + ':</strong>' +
data.message + '</p>';
});
please rectify me where i am doing mistakes
thanks in advance.
In your client code socket must be created with ws protocol. So,
io.connect("http://localhost:8000"); should be io.connect("ws://localhost:8000");

error trying to set up basic chat app with node.js

I am trying to set up a basic chat app with node.js/express/socket.io but for some reason when the client sends message (this works, another client will get the message) it also refreshes the client and the url goes from localhost:3000 to localhost:3000/? (adds /? to end, i don't know what this means). I cant find anything wrong in my code after looking at it for hours. I have:
server.js:
let app = require('express')();
let http = require('http').Server(app);
let io = require('socket.io')(http);
let port = process.env.PORT || 3000;
app.get('/', (req, res) => { res.sendFile(__dirname + '/index.html') });
http.listen(port,() => { console.log('listening on *:' + port) });
io.on('connection', socket => {
socket.on('chat', text => {
io.sockets.emit('chat', `<p>${text}</p>`);
});
});
index.html:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<script src="/socket.io/socket.io.js"></script>
<script src="https://code.jquery.com/jquery-1.11.1.js"></script>
<style>
.chat_view{
height: 300px;
width: 200px;
border: 5px ridge black;
overflow-y: scroll;
}
</style>
</head>
<body>
<div class="chat" id="chat">
<div class="chat_view" id="chat_view">
</div>
<form id="chat_form">
<input type="text" title="chat_input" id="chat_input" style="width: 206px">
</form>
</div>
<script>
let socket = io();
$('#chat_form').submit( () => {
let text = $('#chat_input').val();
socket.emit('chat', text);
});
socket.on('chat', text => {
let chat_view = document.getElementById('chat_view');
chat_view.innerHTML += text;
chat_view.scrollTop = chat_view.scrollHeight;
});
</script>
</body>
</html>
and package.json:
{
"name": "RatScrew",
"version": "0.0.1",
"dependencies": {
"express": "^4.15.3",
"socket.io": "^2.0.2"
}
}
If you're listening to the submit event, that means the form will actually try and POST to the server (which will in your case refresh the screen). If you're using JavaScript to communicate with the server and don't need the form data to get posted by the browser directly, just return false from your callback. Some browsers also want you to call e.preventDefault() as well.
Change your code to:
$('#chat_form').submit((event)=>{
event.preventDefault();
let text = $('#chat_input').val();
socket.emit('chat', text);
});
The default method used when submiting the form is the GET method, which makes the server send index.html again and the page refreshes.
You may want to have a look at https://www.w3.org/TR/html401/interact/forms.html

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>

Resources