Angular 2 cli project -Socket.io not working - socket.io

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")

Related

HTTPS Stream with websockets / Socket.IO (MERN)

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

socket.io not working once deployed on 000webhost

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)
}
})
})

socket.io client 's namespace invalid

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 am getting get polling-xhr.js:157 404 error on my website

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

Display image on pug

I'm new to NodeJS world.
I tried to display image from mongodb using pug and node express.
Please see my code and guide me.
customer.pug
extend layouts
block content
h1.container #{title} of #{customer.full_name}
div.container
p Full Name: #{customer.full_name}
p Address: #{customer.address}
p Age: #{customer.age}
img.imageScr1(src=customer.profileimage, alt=customer.full_name)
app.js
const express = require('express');
const path = require('path');
const router = express.Router();
const mongoose = require('mongoose');
const bodyParser = require('body-parser');
const fs = require('fs');
const multer = require('multer');
// set storage engine
const storage = multer.diskStorage({
destination: function(req, file, cb){
cb(null, './uploads/',)
},
filename: function (req, file, cb) {
cb(null, file.fieldname + Date.now() + path.extname(file.originalname));
}
});
// init upload
const upload = multer({
storage: storage
});
// Middlewares
// middleware for Assets - to set public for assets
app.use(express.static(path.join(__dirname, 'public')));
app.use('/uploads', express.static(path.join(__dirname, 'uploads')));
// route - homepage
app.get('/', function (req, res) {
Customer.find({}, null, function(err, customers) {
if(err){
console.log(err);
} else{
// customers.profileimage = '/' + customers.profileimage;
// console.log('image prefix::: ' + customer.profileimage);
res.render('index', {
title: 'Customer List',
customers: customers
});
}
});
});
app.post('/customer/add', upload.single('profileimage'), function (req, res) {
var customer = new Customer();
customer.full_name = req.body.full_name;
customer.address = req.body.address;
customer.age = req.body.age;
customer.profileimage = req.file.path;
customer.save(function (err) {
if(err){
console.log(err);
} else{
res.redirect('/');
}
});
});
I got following error when render customer.pug view.
error_console
I found that, if I add '\' before image path 'uploads\profileimage1520473825415.jpg', it displays image.
I tried many ways to do that did not work.
Please help me.
Cheers

Resources