Hi I am wondering how I get this behavior:
There is a Button which starts the stream of a specific DIV (already worked using HTTP).
The Stream should be encrypted using HTTPS on localhost.
I changed the connection to HTTPS, created a key and a certificate with this command:openssl req nodes new x509 keyout server.key out server.cert. In the Chrome Dev Tool / Network Section I receive this:
Chrome Screenshot
BUT: the part on the server where I log that a user connected successfully isn't executed and I can't figure out why.
my react component:
import React, { useEffect, useState, useRef } from 'react';
import html2canvas from 'html2canvas';
import io from 'socket.io-client';
const socket = io('https://localhost:8080', {
transports: ['websocket'],
cors: {
origin: 'http://localhost:3000',
},
});
function Stream() {
const [message, setMessage] = useState("Streaming: OFF");
const [streaming, setStreaming] = useState(false);
const sectionRef = useRef(null);
useEffect(() => {
if (!streaming) return;
const intervalId = setInterval(() => {
html2canvas(sectionRef.current).then(canvas => {
socket.emit("streaming", canvas.toDataURL("image/webp"));
});
}, 40);
return () => {
clearInterval(intervalId);
};
}, [streaming]);
const startStream = () => {
setMessage("Streaming: ON");
setStreaming(true);
};
const stopStream = () => {
setMessage("Streaming: OFF");
setStreaming(false);
};
return (
<div>
<h2>Anchor:</h2>
<button onClick={startStream} disabled={streaming}>Start streaming</button>
<button onClick={stopStream} disabled={!streaming}>Stop streaming</button>
<p>{message}</p>
<div ref={sectionRef}>
{/* Replace this with the section of the website you want to stream */}
<p>This is the section of the website that will be streamed</p>
</div>
</div>
);
}
export default Stream;
and the server looks like this:
const https = require('https');
const fs = require('fs');
const cors2 = require('cors');
const options = {
key: fs.readFileSync(\__dirname + '/server.key'),
cert: fs.readFileSync(\__dirname + '/server.cert')
};
const server = https.createServer(options);
const io = require('socket.io')(server);
io.use(cors2({
origin: "\*",
methods: "GET,HEAD,PUT,PATCH,POST,DELETE",
allowedHeaders: "Content-Type,Authorization"
}));
io.on('connection', (socket) =\> {
console.log('a user connected');
socket.on('streaming', (data) =\> {
console.log("received streaming data: ", data);
io.emit('streaming', data);
});
});
server.listen(8080, () =\> console.log('listening on '));
changed browser to Firefox, activated chrome://flags/#allow-insecure-localhost
Related
I read through other post with similar issue which I couldn't solve. I created a simple chat using socket.io, express. On the localhost its working but not on the 000webhost. I'm probably missing a code somewhere.
Tried adding line of codes on the server file and the client side but still couldn't get it to run.
server side
const express = require("express");
const Socket = require("socket.io");
const app = express();
const server = require("http").createServer(app);
const io = Socket(server, {
cors: {
origin: "*",
method: ["GET", "POST"]
}
})
let PORT = 5000;
server.listen(PORT, () => {
console.log("listening on port: ", PORT)
})
const users = [];
io.on("connection", (socket) => {
console.log("connected to", socket.id)
socket.on("adduser", (username)=>{
socket.user = username;
users.push(username);
io.sockets.emit("users", users)
})
socket.on("message", (message)=>{
io.sockets.emit("message_client", {
message,
user: socket.user
})
})
socket.on("disconnect", () => {
console.log("we are disconnecting...: ", socket.user)
if (socket.user){
users.splice(users.indexOf(socket.user), 1)
io.sockets.emit("users", users);
console.log('remaining users: ', users)
}
})
})
I am running on the latest version of socket.io, the server code and client code below works well.
// server
const { Server } = require("socket.io"),
http = require('http');
const httpserver = http.createServer();
io.on("connection", async (socket) => {
socket.on("error", (err) => {
console.log(err.message);
});
socket.on('disconnect', function () {
console.log('socket disconnect');
})
});
const io = new Server(httpserver, {
cors: { origin: "*", methods: ["GET", "POST"],}
});
httpserver.listen(3001, () => {
console.log('listening on *:3001');
});
// client
import { io, Socket } from "socket.io-client";
const socket = io('ws://127.0.0.1:3001', {
transports: ["websocket"]
});
socket.on("connect_error", (err) => {
console.log(`connect_error due to ${err.message}`);
});
then I tried to work with namespace in socket.io
// server
io.of("device").on("connection", async (socket) => {
socket.on("error", (err) => {
console.log(err.message);
});
socket.on('disconnect', function () {
console.log('socket disconnect');
})
});
// client
const socket = io('ws://127.0.0.1:3001/device', {
transports: ["websocket"]
});
running the code gives me an error saying
'connect_error due to Invalid namespace''
I can't figure out what goes wrong
Using ws://127.0.0.1:3001/device means you are trying to reach the namespace named '/advice', which does not exist on the server.
I think you are looking for the path option instead:
const socket = io("ws://127.0.0.1:3001", {
path: "/device",
transports: ["websocket"]
});
References:
https://socket.io/docs/v4/client-initialization/
https://socket.io/docs/v4/client-options/#path
https://socket.io/docs/v4/namespaces/
I have following server code:
const path = require("path");
const http = require("http");
const express = require("express");
const {instrument} = require('#socket.io/admin-ui')
const {jwtDecode, jwtVerify, resignJwt} = require('jwt-js-decode')
const secret =
"xxxxxxx";
const app = express()
const server = http.createServer(app)
const io = require("socket.io")(server, {
cors: {
origin: ["https://admin.socket.io", "http://localhost:3001"],
credentials: true
},
});
let servantID = ''
io.use((socket, next) => {
const header = socket.handshake.headers["authorization"];
jwtVerify(header, secret).then((res) => {
if (res === true)
{
const jwt = jwtDecode(header);
servantID = jwt.payload.iss;
return next()
}
return next(new Error("authentication error"));
});
});
instrument(io, { auth: false });
server.listen(3000, () =>
console.log('connected')
)
io.on('connection', socket => {
socket.on("join", (room, cb) => {
console.log('Joined ' + room);
socket.join(room);
cb(`Joined the best room ${room}`)
});
socket.on('newOrder', function (data) {
socket.to('servant').emit('this', data);
console.log(data);
})
socket.on("thisNew", function (data) {
console.log('this new');
});
socket.on('disconnect', () => {
console.log('user disconnected');
});
})
And client side code:
socket.emit('join', 'servant', message => {
console.log(message)
})
socket.on('this', () => {
console.log('this event')
})
socket.emit('newOrder', 'data')
When I emit like this:
socket.to('servant').emit('this', data);
the client doesn't receive anything, but if I emit without room:
socket.emit('this', data);
the event and data are received on the client side.
What am I doing wrong here?
I am using server.js code
const { startCon } = require('./server/WaConnection')
const http = require('http');
const express = require('express');
const app = express();
const server = http.createServer(app);
const router = express.Router();
const { Server } = require('socket.io');
const io = new Server(server);
app.use(express.json());
app.use(express.urlencoded({ extended: true, limit: '50mb', parameterLimit: 1000000 }))
app.use(router);
require('./server/Routes')(router)
io.on('connection', (socket) => {
socket.on('StartConnection', async (device) => {
startCon(device, socket)
return;
})
socket.on('LogoutDevice', (device) => {
startCon(device, socket, true)
return
})
})
server.listen(process.env.PORT_NODE, () => {
console.log(`Server running on port ${process.env.PORT_NODE}`);
})
I am getting the error again and again that
enter image description here
I will be very thank full if you reslove my issue
Folks,
I have a angular 2 Cli project. Its a simple chatting application. But for some reasons, server is not receiving/sending message to client. There is no compile error and app works but no socket messaging.
Below is the code snippet from each:
Express:
const express = require('express');
const path = require('path');
const http = require('http');
const bodyParser = require('body-parser');
const app = express();
// Parsers for POST data
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: false }));
// Point static path to dist
app.use(express.static(path.join(__dirname, 'dist')));
// Catch all other routes and return the index file
app.get('*', (req, res) => {
res.sendFile(path.join(__dirname, 'dist/index.html'));
});
/**
* Get port from environment and store in Express.
*/
const port = process.env.PORT || '3000';
app.set('port', port);
/**
* Create HTTP server.
*/
const server = http.createServer(app);
//set socket.io for chat
var io = require('socket.io').listen(server);
io.on('connnection', (socket) => {
console.log('user connected');
socket.on('message', (msg) => {
console.log('Message Received: ', msg);
socket.broadcast.emit('message', msg);
});
socket.on('disconnect', () => {
console.log('user has disconnected');
});
});
server.listen(port, () => console.log("server running"));
App component
import { Component } from '#angular/core';
import * as io from "socket.io-client";
#Component({
selector: 'app-root',
templateUrl: './app.component.html',
styleUrls: ['./app.component.css']
})
export class AppComponent {
messages: Array<String>;
chatBox: String;
socket: any;
constructor() {
this.chatBox = "";
this.socket = io("http://localhost:3000");
this.socket.on("message", (msg) => {
this.messages.push(msg);
});
}
send(message) {
this.socket.emit("message", message);
this.chatBox = "";
}
}
Html:
<ul>
<li *ngFor="let item of messages">{{item}}</li>
</ul>
<input [(ngModel)]="chatBox" autocomplete="off" />
<button (click)="send(chatBox)">Send</button>
I would appreciate any help or hint to resolve this.
If I simple express based server with html chatting works fine.
Thanks
There's no code for connection to socket at all.
Change
this.socket = io("http://localhost:3000");
to
this.socket=io.connect("http://localhost:3000")