So I trying to deposit data to user as a call made, and I have two problems.
First, when user connect its spams "user connected"
Second, I dont get any data on the page.
Here's the code:
bin/www:
var app = require('../app');
var debug = require('debug')('myapp:server');
var http = require('http');
var socketHandler = require('../handlers/sockethandler');
var io = socketHandler.io;
var server = http.createServer(app);
io.attach(server);
sockethandler.js:
var socket_io = require('socket.io');
var io = socket_io();
var socketHandler = {};
socketHandler.io = io;
io.on('connection', (socket) => {
console.log('a user connected');
socket.on('disconnect', () => {
console.log('user disconnected');
});
});
module.exports = socketHandler;
emit data post:
var socketHandler = require('./sockethandler');
var io = socketHandler.io;
var exten = evt.exten, statustext = evt.statustext;
io.emit('extenstate', {exten, statustext});
client.js:
var socket = io("http://192.168.168.49:3000");
socket.on('extenstate', function(state) {
var li = document.createElement('li');
console.log(state.exten);
var Extension = document.createElement('h4');
var Status = document.createElement('h4');
Extension.textContent = 'Extension:' + state.exten;
Status.textContent = 'Status:' + state.statustext;
li.appendChild(Extension);
li.appendChild(Status);
document.getElementById('phone-calls').appendChild(li);
});
route:
var express = require('express');
var router = express.Router();
/* GET home page. */
router.get('/', function(req, res, next) {
res.render('data', { title: 'Realtime Sender' });
});
module.exports = router;
ejs:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Lonestar - <%= title %></title>
</head>
<body>
<div id="phone-calls"></div>
<script src="https://cdn.socket.io/socket.io-1.3.5.js"></script>
<script src="client.js"></script>
</body>
</html>
Related
I'm learning the socket.io library in Node.js and I can't make the server receive data, only send. During tests I noticed that the io.on listener function isn't even being called, and I don't know where's my mistake. What exactly works and what doesn't is marked with commentaries in the code bellow.
My server-side code:
"use strict";
const http = require("http");
const express = require("express");
const { Server } = require("socket.io");
const { log } = console;
const app = express();
const server = http.createServer(app);
const io = new Server(server);
app.use(express.urlencoded({extended: false}));
app.use(express.json());
app.use(express.static(__dirname + "/public"));
io.on("connect", socket => {
const { id } = socket;
io.emit("receiveMsg", id); // This works
})
io.on("sendMsg", msg => { // This doesn't work
log("sendMsg: " + msg);
});
server.listen(8080);
My client-side code:
const socket = io();
const { log } = console;
socket.on("receiveMsg", msg => { // This works
log("receiveMsg: " + msg);
});
const sendMsg = () => {
const msg = document.querySelector("#msg").value;
socket.emit("sendMsg", msg); // This doesn't work
}
My client-side 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>Test</title>
</head>
<body>
<h1>Hello, world!</h1>
<input type="text" id="msg" placeholder="msg">
<button onclick="sendMsg()">send</button>
<script src="https://cdnjs.cloudflare.com/ajax/libs/socket.io/4.1.3/socket.io.js"></script>
<script>
// Client-side code here
</script>
</body>
</html>
based on the doc https://socket.io/docs/v4/client-socket-instance/
the connection event is connection on server side, and connect on client side
// server-side
io.on("connection", (socket) => {
console.log(socket.id); // x8WIv7-mJelg7on_ALbx
});
// client-side
socket.on("connect", () => {
console.log(socket.id); // x8WIv7-mJelg7on_ALbx
});
for Emit events, if you see here https://socket.io/docs/v4/emitting-events/
it seems requires us to put the subscription event inside connection block
// server-side
io.on("connection", (socket) => {
socket.on("hello", (arg) => {
console.log(arg); // world
});
});
// client-side
socket.emit("hello", "world");
so maybe you can try to change your server code
io.on("connection", (socket) => {
socket.on("sendMsg", msg => { // This doesn't work
log("sendMsg: " + msg);
}
});
it uses socket.on, not io.on on server side
I've seen many questions and none of them fix my problem.
Here's my JS (app.js) code:
var express = require('express');
var app = express();
var serv = require('http').Server(app);
app.get('/', function(req, res) {
res.sendFile(__dirname + '/client/index.html');
});
app.use('/client', express.static(__dirname + '/client'));
serv.listen(2000);
console.log('Server has started.');
var socket_list = {};
var io = require('socket.io')(serv, {});
io.sockets.on('connection', function(socket) {
console.log('Socket Connection');
socket.id = Math.random();
socket.x = 0;
socket.y = 0;
socket_list = socket.id = socket;
});
setInterval(function() {
for(var i in socket_list) {
var socket = socket_list[i];
socket.x++;
socket.y++;
socket.emit('newPosition', {
x: socket.x,
y: socket.y
});
}
}, 1000/25);
Here is my HTML (index.html) code:
<!DOCTYPE html>
<html>
<head>
<title>Multiplayer | HTML5</title>
<script src="https://cdn.socket.io/socket.io-1.4.5.js"></script>
</head>
<body>
<canvas id="ctx" width="512" height="512" style="border: 1px solid #000;"></canvas>
<script type="text/javascript">
var ctx = document.getElementById('ctx').getContext('2d');
ctx.font = '24px Calibri';
var socket = io();
socket.on('newPosition', function(data) {
ctx.clearRect(0,0,500,500);
ctx.fillText('P', data.x, data.y);
})
</script>
</body>
</html>
I'm following this tutorial: https://www.youtube.com/watch?v=_GioD4LpjMw&feature=youtu.be
It's 3 years old but everything is going smoothly until 4:47 in the video ^^.
Using the exact same code above ^^ I get this:
You are replacing Socket list object with a Socket object. Also use io.on.
io.sockets.on('connection', function(socket) {
console.log('Socket Connection');
socket.id = Math.random();
socket.x = 0;
socket.y = 0;
socket_list = socket.id = socket;
});
You need to change it to,
io.on('connection', function(socket) {//use io.on
console.log('Socket Connection');
socket.id = Math.random();
socket.x = 0;
socket.y = 0;
socket_list[socket.id] = socket;//fix this error
});
Change io.emit to socket.emit.
socket.emit('newPosition', {
x: socket.x,
y: socket.y
});
I get images from python opencv then I want show images to user as video stream on browser.
Images came on sequence. I do this in python Flask with "multipart/x-mixed-replace" but I can`t find same function on node js.
//index.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
<script src="https://cdnjs.cloudflare.com/ajax/libs/socket.io/2.2.0/socket.io.js"></script>
</head>
<body>
<img id="image">
<script>
const socket = io.connect('http://localhost:3000');
socket.on('image', (image) => {
const imageElement = document.getElementById('image');
console.log(imageElement);
imageElement.src = `data:image/jpeg;base64,${image}`;
});
</script>
</body>
</html>
//server.js
const express = require('express');
const cv = require('opencv4nodejs');
const app = express();
const path = require('path');
const FPS = 30;
const server = require('http').Server(app);
const io = require('socket.io')(server);
const wCap = new cv.VideoCapture(0);
app.get('/', function (req, res) {
res.sendFile('index.html', {root: __dirname});
});
setInterval(() => {
const frame = wCap.read();
const image = cv.imencode('.jpg', frame).toString('base64');
io.emit('image', image)
}, 1000/FPS);
server.listen(3000);
I'm fairly new to Nodejs and I'm building an app that ssh to a remote machine and get a tail -f of a log file.
The lines of the log file I'm receiving I'm sending to the client via socket-io (ver. 2.0.3)
Now I'm facing a problem that when a second browser tries to tail a different log, the new log is sent to both of the browsers instead of only the one who made the request.
I'm not sure if it's a problem with my socket-io code or the child_process.
Here's the server:
const express = require('express'),
app = express(),
path = require('path'),
bodyParser = require('body-parser'),
logger = require('morgan'),
server = require('http').Server(app),
io = require('socket.io')(server),
spawn = require('child_process').spawn,
events = require('events'),
eventEmitter = new events.EventEmitter();
// Fix body of requests
app.use(bodyParser.urlencoded({extended: true}));
app.use(bodyParser.json());
// Log the requests
app.use(logger('dev'));
// Serve static files
app.use(express.static(path.join(__dirname, '.')));
// Add a basic route – index page
app.get('/', function (req, res) {
res.sendFile(path.join(__dirname, 'index.html'));
});
io.on('connection', (socket) => {
console.log(`client connected ${socket.client.id}`);
eventEmitter.on('tail', (data) => {
socket.tail = spawn('ssh', ['root#' + 'quality-p.company.com', 'tail -f', data.service], { shell: true });
socket.tail.stdout.on('data', (data) => {
console.log(`got new data ${data.toString()}`);
socket.emit('newLine', {line: data.toString().replace(/\n/g, '<br />')});
});
});
});
app.get('/tail', (req, res) => {
eventEmitter.emit('tail', req.query);
res.sendStatus(200);
});
// Bind to a port
server.listen(3005, () => {
console.log('running on localhost:' + 3005);
});
Client:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<script src="./node_modules/socket.io-client/dist/socket.io.js"></script>
<script src="https://code.jquery.com/jquery-3.2.1.min.js"></script>
<script>
$(() => {
let socket = io();
socket.on('connect', () => {
console.log('connected');
});
socket.on('newLine', (data) => {
console.log(`new data: ${data.line}`);
$("#tailing").append(data.line);
});
$('#tail').click(() => {
$.get('/tail', {
service: $('#service').val()
});
});
});
</script>
<title>Title</title>
</head>
<body>
<select id="service">
<option id="tnet" value="/var/log/tnet">tnet</option>
<option id="consul" value="/var/log/consul">consul</option>
</select>
<button id="tail">tail</button>
<div id="tailing" style="background-color: antiquewhite;">
</div>
</body>
</html>
Server
const express = require('express'),
app = express(),
path = require('path'),
bodyParser = require('body-parser'),
logger = require('morgan'),
server = require('http').Server(app),
io = require('socket.io')(server),
spawn = require('child_process').spawn;
// Fix body of requests
app.use(bodyParser.urlencoded({
extended: true
}));
app.use(bodyParser.json());
// Log the requests
app.use(logger('dev'));
// Serve static files
app.use(express.static(path.join(__dirname, '.')));
// Add a basic route – index page
app.get('/', function(req, res) {
res.sendFile(path.join(__dirname, 'index.html'));
});
var tails = {};
io.on('connection', (socket) => {
console.log(`client connected ${socket.client.id}`);
socket.on('tail', (data) => {
socket.join(data.service);
if (typeof tails[data.service] == "undefined") {
tails[data.service] = spawn('ssh', ['root#' + 'quality-p.company.com', 'tail -f', data.service], {
shell: true
});
tails[data.service].stdout.on('data', (data) => {
console.log(`got new data ${data.toString()}`);
io.to(data.service).emit('newLine', {
line: data.toString().replace(/\n/g, '<br />')
});
});
}
});
});
// Bind to a port
server.listen(3005, () => {
console.log('running on localhost:' + 3005);
});
Client
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<script src="./node_modules/socket.io-client/dist/socket.io.js"></script>
<script src="https://code.jquery.com/jquery-3.2.1.min.js"></script>
<script>
$(() => {
let socket = io();
socket.on('connect', () => {
console.log('connected');
});
socket.on('newLine', (data) => {
console.log(`new data: ${data.line}`);
$("#tailing").append(data.line);
});
$('#tail').click(() => {
socket.emit('tail', {
service: $('#service').val()
});
});
});
</script>
<title>Title</title>
</head>
<body>
<select id="service">
<option id="tnet" value="/var/log/tnet">tnet</option>
<option id="consul" value="/var/log/consul">consul</option>
</select>
<button id="tail">tail</button>
<div id="tailing" style="background-color: antiquewhite;">
</div>
</body>
</html>
Here is my sample code:
File: index.js
var express = required('express');
var app = express();
app.get("/", function(req, res){
...
...
res.render("/index", {
list: data
});
});
File: test.js
var chai = require('chai');
var chaiHttp = require('chai-http');
var server = require('../index');
var should = chai.should();
chai.use(chaiHttp);
describe('Homepage', function(done){
it('should render index view', function(done){
chai.request(server.app)
.get("/")
.end(function(err, res){
console.log(res.body);
});
});
});
The console.log(res.body) shows output as {}. How can I get the local list variable to show in the output? I want to test if this local list variable has any data in my test.js file.
Option 1. You should use res.json([body]) to send the list data to your test case.
E.g.
index.js:
var express = require('express');
var app = express();
app.get('/', function (req, res) {
const data = ['a', 'b'];
res.json({ list: data });
});
module.exports = { app };
index.test.js:
var chai = require('chai');
var chaiHttp = require('chai-http');
var server = require('./index');
var should = chai.should();
chai.use(chaiHttp);
describe('Homepage', function (done) {
it('should render index view', function (done) {
chai
.request(server.app)
.get('/')
.end(function (err, res) {
console.log(res.body);
done();
});
});
});
test result:
Homepage
{ list: [ 'a', 'b' ] }
✓ should render index view
1 passing (28ms)
Option 2. You should assert the view rendered correctly with your list data.
index.js:
var express = require('express');
var path = require('path');
var app = express();
app.set('views', path.resolve(__dirname, './views'));
app.set('view engine', 'ejs');
app.get('/', function (req, res) {
const data = ['a', 'b'];
res.render('index', { list: data });
});
module.exports = { app };
views/index.ejs:
<!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>
<% for (let v of list) { %>
<p><%= v %></p>
<% } %>
</body>
</html>
index.test.js:
const { expect } = require('chai');
var chai = require('chai');
var chaiHttp = require('chai-http');
var server = require('./index');
var should = chai.should();
chai.use(chaiHttp);
describe('Homepage', function (done) {
it('should render index view', function (done) {
chai
.request(server.app)
.get('/')
.end(function (err, res) {
console.log(res.text);
done();
});
});
});
test result:
Homepage
<!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>
<p>a</p>
<p>b</p>
</body>
</html>
✓ should render index view
1 passing (32ms)