I have web socket server and http server, and I want to tell socketio server to emit a msg to the client only if an event was emitted using EventEmitter Class, the problem is when I open 2 tabs in browser I noticed that the event was send to all users (broadcasting)
here is the both servers:
const server = require('http').createServer(handler)
, io = require('socket.io')(server)
, url = require('url')
, fs = require('fs')
, EventEmitter = require('events')
, emitter = new EventEmitter();
server.listen(3000);
function handler(req, res) {
var route = url.parse(req.url).pathname;
if (route === '/') {
var stream = fs.createReadStream(__dirname + '/index.html');
stream.pipe(res);
} else if (route === '/testSocket') {
var stream = fs.createReadStream(__dirname + '/test.html');
stream.pipe(res);
// emit event after 5s, the handler is inside socketio server
setTimeout( function() {
emitter.emit('fromEmitterToSocketServer', 'Msg');
}, 5000);
} else {
res.writeHead(404, {"Content-Type": "text/plain"});
res.end('404');
}
}
io.on('connection', function (socket) {
// handle event and then send data to the user
emitter.on('fromEmitterToSocketServer', function(data) {
// here I noticed that socketio emit the event to all users
socket.emit('fromSocketServerToClient', data);
});
});
Index.html:
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>Index</title>
</head>
<body>
<h1>Index</h1>
<script src="https://cdnjs.cloudflare.com/ajax/libs/socket.io/2.0.3/socket.io.js"></script>
<script>
var socket = io('//localhost:3000');
socket.on('fromSocketServerToClient', function (data) {
console.log(data);
});
</script>
</body>
</html>
test.html:
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>Test socketIO</title>
</head>
<body>
<h1>Test socketIO</h1>
<script src="https://cdnjs.cloudflare.com/ajax/libs/socket.io/2.0.3/socket.io.js"></script>
<script>
var socket = io('//localhost:3000');
socket.on('fromSocketServerToClient', function (data) {
console.log(data);
});
</script>
</body>
</html>
If I open two tabs and go to http://localhost:3000 and http://localhost:3000/testSocket I figure out that the msg is logged into the both of them
Thanks
Related
I am planning to use the camera to capture images stream and make it can be shown in the web, just like a live stream. I have done the client part and the server part can receive the base64 data of each captured image. Below is the server code and the message represents the base64 data. My question is that how can I transfer the "message" to html file so that it can be used as src to locate the images? THX.
let WebSocketServer = require('ws').Server,
wss = new WebSocketServer({ port: 3303 });
wss.on('connection', function (ws) {
console.log('client is connected');
ws.on('message', function (message) {
wss.clients.forEach(function each(client) {
client.send(message);
});
console.log(message);
});
})
Below is the code of html file. What should I use to fill the "src" part?
<!DOCTYPE html>
<html >
<head>
<meta charset="UTF-8">
<title>Title</title>
</head>
<body>
<div>
<img id="resImg" src = ""> </img>
</div>
<script src="jquery.min.js" ></script>
<script>
let ws = new WebSocket("ws://127.0.0.1:3303/");
ws.onopen = function(evt) {
console.log("Connection open ...");
ws.send("Hello WebSockets!");
};
ws.onmessage = function(evt) {
$("#resImg").attr("src",evt.data);
console.log( "Received Message: " + evt.data);
// ws.close();
};
ws.onclose = function(evt) {
console.log("Connection closed.");
};
</script>
</body>
</html>
I am working on a node.js app where I am using socket.io to send data to multiple clients but the socket is only able to send data to one client i.e if I open my webpage in two tabs its not working in both the tabs but when I open just 1 tab of webpage it is able to transmit the data.I dont know why? Can someone help,Here's my code:
server.js
var http = require("http"),
io = require("socket.io"),
fs = require("fs"),
util = require("util");
var backlog_size = 2000;
var filename = process.argv[2];
if (!filename) return util.puts("Usage: node <server.js> <filename>");
var linesCount = 0;
// -- Node.js HTTP Server ----------------------------------------------------------
server = http.createServer(function (req, res) {
console.log(req.url)
filePath = req.url
if(filePath=="/"){
filePath='./index.html'
fs.readFile(filePath, function (err, data) {
if (err) {
res.writeHead(500);
return res.end('Error loading ' + filePath);
}
res.writeHead(200);
res.end(data);
});
}
else
{
if(filePath=="/client"){
filePath = './client.html';
fs.readFile(filePath, function (err, data) {
if (err) {
res.writeHead(500);
return res.end('Error loading ' + filePath);
}
res.writeHead(200);
res.end(data);
});
}}
});
server.listen(8000, "0.0.0.0");
var fsTimeout
var textToSend=""
// -- Setup Socket.IO ---------------------------------------------------------
var socket = io(server, {
cors: {
origin: "*",
},
});
socket.on("connection", function (client) {
fs.watchFile(filename, function (curr, prev) {
console.log("file changed");
if (prev.size > curr.size) return { clear: true };
if(!fsTimeout){
if(prev.ctime.getTime() != curr.ctime.getTime())
{
console.log("file changed")
var stream = fs.createReadStream(filename, {
start: prev.size,
end: curr.size,
});
stream.on("data", function (lines) {
console.log(lines.toString());
textToSend+=lines.toString();
textlen=textToSend.split("\n").length;
// count=lines.toString().split("\n").length
// linesCount += count;
// console.log(linesCount);
console.log(textlen)
if(textlen<10)
{
console.log("me")
client.emit("tail", { lines: lines.toString("utf-8").split("\n") });}
else
{
console.log("client")
client.emit("room", { lines: textToSend.toString("utf-8").split("\n") }); };
});
}
fsTimeout = setTimeout(function() { fsTimeout=null }, 5000)}
}
);
});
In the above code I have added 2 clients,1 page is index.html and other is client.html and both are opening in the browser and getting connected to the socket but the data is not transmitting to any of them.Here's are my client codes:
index.html
<!DOCTYPE html>
<html>
<head>
<title>Websockets tail Server</title>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.4.2/jquery.min.js"></script>
<script type="text/javascript" src="/socket.io/socket.io.js"></script>
</head>
<body>
<div id="info" class="trebuchet"></div>
<div id="tail" class="monospace selection"></div>
<script type="text/javascript">
(function() {
var lines = 0, notice = $("#info"), buffer = $('#tail');
var socket = io.connect('http://127.0.0.1:8000/');
socket.on('connect', function() {
console.log('Connected to stream');
});
socket.on('room', function(msg) {
console.log("Message:");
console.dir(msg);
buffer.append(msg.lines.join('<br/>'));
buffer.scrollTop(lines*100);
lines = lines + msg.lines.length;
});
})();
</script>
</body>
</html>
client.html
<!DOCTYPE html>
<html>
<head>
<title>Websockets tail Server</title>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.4.2/jquery.min.js"></script>
<script type="text/javascript" src="/socket.io/socket.io.js"></script>
</head>
<body>
<div id="info" class="trebuchet"></div>
<div id="tail" class="monospace selection"></div>
<script type="text/javascript">
(function() {
var lines = 0, notice = $("#info"), buffer = $('#tail');
var socket = io.connect('http://127.0.0.1:8000/');
socket.on('connect', function() {
console.log('Connected to stream');
});
socket.on('tail', function(msg) {
console.log("Message:");
console.dir(msg);
buffer.append(msg.lines.join('<br/>'));
buffer.scrollTop(lines*100);
lines = lines + msg.lines.length;
});
})();
</script>
</body>
</html>
Both the html files above are my clients and I want them to listen to my socket server but they are not but when I remove one of the clients,it works.
Any help will be appreciated
ii'm new to node.js and socket.io. I'm trying to track gesture from phone to pc. I'm correctly sending text but i'm not able to send data
index.html
<!DOCTYPE html>
<html>
<meta name="viewport" content="width=device-width, initial-scale=1">
<!-- <body ontouchstart="showCoordinates(event)" ontouchmove="showCoordinates(event)"> -->
<body ontouchstart="countTouches(event)" ontouchend="countTouches(event)">
<script src="/socket.io/socket.io.js"></script>
<script>
var socket = io.connect();
function countTouches(event) {
var x = event.touches.length;
socket.emit('clicked');
}
socket.on('buttonUpdate', function(countTouches){
document.getElementById("demo").innerHTML = x;
});
</script>
</body>
</html>
server.js
io.on('connection', function(client){
client.on('clicked', function(data) {
//send a message to ALL connected clients
io.emit('buttonUpdate');
console.log('click!');
});
});
http.listen(3000, function() {
console.log('listening on localhost:3000');
});
I got the touch count in my phone but error in the pc
Error from console: Uncaught ReferenceError: x is not defined
You are not sending the data on emit from the server and in the client you are receiving countTouches but providing value of x. Try with the below code.
io.on('connection', function(client){
client.on('clicked', function(data) {
//send a message to ALL connected clients
console.log(data);
io.emit('buttonUpdate',data);
console.log('click!');
});
});
http.listen(3000, function() {
console.log('listening on localhost:3000');
});
<!DOCTYPE html>
<html>
<meta name="viewport" content="width=device-width, initial-scale=1">
<!-- <body ontouchstart="showCoordinates(event)" ontouchmove="showCoordinates(event)"> -->
<body ontouchstart="countTouches(event)" ontouchend="countTouches(event)">
<script src="/socket.io/socket.io.js"></script>
<script>
var socket = io.connect();
function countTouches(event) {
var x = event.touches.length;
socket.emit('clicked',x);
}
socket.on('buttonUpdate', function(countTouches){
document.getElementById("demo").innerHTML = countTouches;
});
</script>
</body>
</html>
I have read a lot of tutorial, and sample code to send data from a node.js class to an html page and show this data.
such as link1, link2,link3,link4,link5
and some others.
I am getting some data from UDP listener and need to send it after some processing to an html page to show it. here is my code:
The udp receiver:
var server_port = process.env.OPENSHIFT_NODEJS_PORT || 8080
var server_ip_address = process.env.OPENSHIFT_NODEJS_IP || '127.0.0.1'
var http = require('http'),
dgram = require('dgram'),
socketio = require('socket.io'),
fs = require('fs');
var html = fs.readFileSync(__dirname + '/html/showMap.html');
var app = http.createServer(function(req, res) {
res.writeHead(200, {
'Content-type': 'text/html'
});
res.end(html);
io.sockets.emit('welcome', { message: 'Welcome!'});
}).listen( server_port, server_ip_address, function() {
console.log('Listening');
});
var io = socketio.listen(app),
socket = dgram.createSocket('udp4');
socket.on('message', function(content, rinfo) {
console.log('got message', content, 'from', rinfo.address, rinfo.port);
io.sockets.emit('udp message', 'content' /*content.toString()*/);
});
socket.bind(5001);
and my html page which is called 'showMap.html'
<html>
<head>
<meta name="viewport" content="initial-scale=1.0, user-scalable=no">
<meta charset="utf-8">
<title>Get Data</title>
<script src="/socket.io/socket.io.js"></script>
</head>
<body>
<div id="results"> This text will change </div>
<div id="date">sample another temp text</div>
<script>
// client code here
var socket = io.connect('localhost', {port: 8080});
socket.on('udp message', function(message) {
console.log(message)
document.getElementById("date").innerHTML = "My new text!";
});
socket.on('welcome', function(data) {
document.getElementById("results").innerHTML = data.message;
});
</script>
</body>
</html>
but by sending packet, html page has not changed.
Here is my console log of running code:
Atis-MacBook-Pro:startWithNode muser$ npm start
StartWithNodejs#1.0.0 start /Volumes/Project/Project/NodeJS/startWithNode
node index.js
Listening got message from 127.0.0.1 64047
What is wrong in my code?
I tested this locally. In your HTML file I made two changes and it worked.
1 - Replace io.connect('localhost', {port: 8080}); with io.connect('localhost:8080');
2 - There was a strange \u200b character at the end of the document.getElementById("date").innerHTML = "My new text!"; line. I deleted that and ended up with:
<html>
<head>
<meta name="viewport" content="initial-scale=1.0, user-scalable=no">
<meta charset="utf-8">
<title>Get Data</title>
<script src="/socket.io/socket.io.js"></script>
</head>
<body>
<div id="results"> This text will change </div>
<div id="date">sample another temp text</div>
<script>
// client code here
var socket = io.connect('localhost:8080');
socket.on('udp message', function(message) {
console.log(message)
document.getElementById("date").innerHTML = "My new text!";
});
socket.on('welcome', function(data) {
document.getElementById("results").innerHTML = data.message;
});
</script>
</body>
</html>
Which replaces the content of results.
in this example you will be able to get JSON data from php file and send it to all connected clients.
RunThisFileThroughNodeJs.js
var app = require('express')();
var http = require('http').Server(app);
var io = require('socket.io')(http);
var port = process.env.PORT || 3000;
var request = require("request")
var url = "http://localhost/api/index.php";
events = require('events'),
serverEmitter = new events.EventEmitter();
app.get('/', function(req, res){
res.sendFile(__dirname + '/index.html');
});
io.on('connection', function(socket){
setInterval(
function(){
request({
url: url,
json: true
}, function (error, response, body) {
if (!error && response.statusCode === 200) {
io.emit('chat message', body);
}
});
},5000);
});
http.listen(port, function(){
console.log('listening on *:' + port);
});
Don't Forget to install express , request for nodejs
Now make this file i will call it index.html so the response of my file will be here.
index.html
<!doctype html>
<html>
<head>
<title>Prices API</title>
<script src="http://localhost/js/socket.io.js"></script>
</head>
<body>
<div id="price_list"></div>
<script>
var socket = io();
socket.on('chat message', function(msg){
document.getElementById("price_list").innerHTML = JSON.stringify(msg);
console.log(msg);
});
</script>
</body>
</html>
Please I have this small demo of a collaborative editor in a pub/sub fashion.
Scenario:
Server :S
Clients : A, B
A sends text S.
S receives text and brodcast to B.
B sends text to S.
S receives text and brodcast to A, A receive text, but document.getElementById is not updting the display.
I suspect the problem is with javascript execution order...
I am bit confused, can someone points me what goes wrong with my client ?
Server:
var app = require('express')();
var http = require('http').createServer(app)
var io = require('socket.io').listen(http);
//Server accepting connect on this port
http.listen(3000);
//Establishing connection to client and disconnecting
io.sockets.on('connection', function(socket){
console.log('Connected to a new client');
socket.on('room', function(room) {
socket.join(room);
console.log('join room '+ room);
});
socket.on('disconnect', function(){
socket.disconnect();
console.log('Disconnected from a client');
});
var room= 'room1';
//Data exchange between client and server
//Server receives new data from a client and broadcast it to others
socket.on('client_character',function(msg){
//receive data
console.log('Data from client'+msg.buffer);
socket.in(room).broadcast.emit('server_character',msg.buffer);
//socket.broadcast.to(room).emit('server_character', msg.buffer);
//socket.to(room).emit('server_character',msg.buffer);
});
});
Client:
Run separately on Apache server
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8"/>
<title>Client</title>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="https://cdn.socket.io/socket.io-1.4.5.js"></script>
<link rel="stylesheet" type="text/css" href="styles/style.css">
</head>
<body>
<textarea id="notepad"></textarea><br/>
<script>
$(function () {
var socket = io.connect('http://localhost:3000',
{'sync disconnect on unload':false});
var room = "room1";
socket.on('connect', function() {
socket.emit('room', room);
});
//receive character from server
socket.on('server_character',function(content){
console.log('From Server:'+ content);
document.getElementById('notepad').innerHTML=content;
});
//For each typed character
$('#notepad').on('keypress',function(){
var character= $('#notepad').val();
//send character to servers
socket.emit('client_character',{buffer:character});
console.log('To Server:'+ {buffer:character} );
});
});
</script>
</body>
</html>
style.css:
#notepad{
height:500px;
width:500px;
font-size: 14px;
color: brown;
}
package.json:
{
"name": "collaborative",
"version": "0.0.1",
"description": "none",
"dependencies": {
"express": "^4.10.2",
"socket.io": "^1.4.5"
}
}
Reference Demo:
[https://www.youtube.com/watch?v=I0iikz1F1Lk][1]
I did some thanges in tour code for fix one bug in input and add more logs and this is working here with FF and Chrome ( i dont have IE here )
Server:
var app = require('express')();
var http = require('http').createServer(app);
var io = require('socket.io').listen(http);
//Server accepting connect on this port
http.listen(3000);
//Establishing connection to client and disconnecting
io.sockets.on('connection', function(socket){
console.log('Connected to a new client');
socket.on('error', function(err) {
//here i change options
console.log('Error!', err);
});
socket.on('room', function(room) {
socket.join(room);
console.log('join room: '+ room);
});
socket.on('disconnect', function(){
// socket.disconnect();
console.log('Disconnected from a client');
});
var room= 'room1';
//Data exchange between client and server
//Server receives new data from a client and broadcast it to others
socket.on('client_character',function(msg){
//receive data
console.log('Data from client: '+msg.buffer);
socket.in(room).broadcast.emit('server_character',msg.buffer);
//socket.broadcast.to(room).emit('server_character', msg.buffer);
//socket.to(room).emit('server_character',msg.buffer);
});
});
Client:
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8"/>
<title>Client</title>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="https://cdn.socket.io/socket.io-1.4.5.js"></script>
<link rel="stylesheet" type="text/css" href="styles/style.css">
</head>
<body>
<textarea id="notepad"></textarea><br/>
<script>
$(function () {
var socket = io.connect('http://localhost:3000',
{'sync disconnect on unload':false});
var room = "room1";
socket.on('connect', function() {
socket.emit('room', room);
});
//receive character from server
socket.on('server_character',function(content){
console.log('From Server:'+ content);
document.getElementById('notepad').innerHTML=content;
});
//For each typed character
$('#notepad').on('keyup',function(){
var character= $('#notepad').val();
//send character to servers
socket.emit('client_character', {buffer:character});
console.log('To Server:', { buffer:character } );
});
});
</script>
</body>
</html>