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>
Related
I've been having this issue for the past 6 or so hours and I can't figure it out. I followed examples perfectly, yet when I run my server, the console.log output does not get displayed on the html page. This is my first time messing with Node.js. Here is the code:
Server:
require('dotenv').config()
var Twitter = require ('twitter');
var app = require('express')();
var http = require('http').Server(app);
var io = require('socket.io').listen(app);
var port = process.env.PORT || 8000;
var express = require ('express');
var events = require('events')
var eventEmitter = new events.EventEmitter();
// add API keys to .env file. .env_sample for details
var T = new Twitter({
consumer_key: process.env.CONSUMER_KEY,
consumer_secret: process.env.CONSUMER_SECRET,
access_token_key: process.env.ACCESS_TOKEN_KEY,
access_token_secret: process.env.ACCESS_TOKEN_SECRET
});
app.get('/', function(req, res){
res.sendFile(__dirname + '/index.html');
});
app.use(express.static(__dirname + '/public'));
eventEmitter.on('logging', function(message) {
io.emit('log_message', message);
});
http.listen(port, function(){
console.log('listening on *:' + port);
});
// Override console.log
var originConsoleLog = console.log;
console.log = function(data) {
eventEmitter.emit('logging', data);
originConsoleLog(data);
};
// code for test.
setInterval(function() {
console.log('X: ' + Math.random());
}, 2000);
/*T.get('statuses/home_timeline', function(error, tweets, response) {
if(error) throw error;
tweets.render
console.log(tweets); // General Tweet Timeline
});*/
HTML:
<!doctype html>
<html lang = "eng">
<head>
<meta charset="UTF-8">
<title> Twitter Client</title>
<link rel="stylesheet" type = "text/css" href="/css/index.css">
</head>
<body>
<img class="logo" src="/images/Twitter_Logo_Blue.png" height = "250" width = "250" alt="blue_bird">
<h1> Using this simple twitter client, the user can view general tweets, specify a specific twitter handle, and search tweets by text. </h1>
<ul id = "messages"></ul>
<script src="https://cdn.socket.io/socket.io-1.2.0.js"></script>
<script src="https://code.jquery.com/jquery-1.11.1.js"></script>
<script>
$(function(){
var socket = io();
socket.on('log_message', function(msg){
$('#messages').append($('<li>').text(msg));
});
});
</script>
</body>
</html>
For the life of me I can't figure out what's going on, and this project is due shortly. Any help would be GREATLY appreciated.
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
I was trying to implement Quill API with socket.io to build a realtime editor. I was able to get the Delta emitted, but quill.updateContents() does not seems to update the text editor with the emitted Delta op data.
Here is my code:
index.html (client side)
<!DOCTYPE html>
<html>
<head>
<title>Connected Clients</title>
<!--<meta charset="UTF-8"> -->
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script>
<!--<script type="text/javascript" src="jquery.js"></script> -->
<script src="/socket.io/socket.io.js"></script>
<link href="https://cdn.quilljs.com/1.1.1/quill.snow.css" rel="stylesheet">
<link href="https://cdn.quilljs.com/1.1.2/quill.snow.css" rel="stylesheet">
</head>
<body>
<div id="editor">
<p>Hello World!</p>
<p>Some initial <strong>bold</strong> text</p>
<p><br></p>
</div>
<span id="insertHere"></span>
<script src="https://cdn.quilljs.com/1.1.2/quill.js"></script>
<script>
$(document).ready(function () {
var quill = new Quill('#editor', {
theme: 'snow'
});
var socket = io();
socket.on('updated_para',function(data){
var el = document.getElementById('insertHere');
el.innerHTML = data;
var ops = data;
quill.updateContents(data);
});
quill.on('text-change', function(delta, source) {
var para = quill.getContents();
socket.emit('para',{delta:JSON.stringify(delta.ops)});
});
});
</script>
</body>
</html>
index.js (server side)
var app = require('express')();
var http = require('http').Server(app);
var io = require('socket.io')(http);
app.get('/', function(req, res){
res.sendFile(__dirname + '/index.html');
});
http.listen(3000, function(){
console.log('listening on *:3000');
});
io.sockets.on('connection', function(socket){
console.log('a user connected');
socket.on('disconnect', function(){
console.log('user disconnected');
});
socket.on('para',function(data){
io.emit('updated_para',data.delta);
console.log('message: ' + data.delta);
});
});
I will really appreciate your help!
i think you forget to convert the json code back to an object..
you convert the data before sending to your socket server to a json string. So the date you receive would alway be a string instead of an json.object.
// Replace
var ops = data;
quill.updateContents(data);
// with
var ops = JSON.parse(data);
quill.updateContents(data);
i'm planning to make a similar kind of editor, so i can watch / share code editing.
Kind Regard.
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>
I send 1 by serialport on arduino to web by node and socket.io. The problem is that when I send the data I have:
Data: [object Object]
Data: [object Object]
...
but I want something like that
Data: 1
Data: 1
...
There is no value "1", I try to send string and still the same. Why is that?
Program works ok but this value problem is wall for me to go further I have a message in console:
userk#user-k52j:~/sio$ node app.js
http.listen
Port OPEN.
express deprecated res.sendfile: Use res.sendFile instead app.js:10:9
Socket.io connected.
But when I change sendfile to sendFile the program crash.
This is my programs:
Arduino:
void setup(){Serial.begin(9600);}
void loop(){
Serial.println(1);
delay(2000);
}
app.js
var app = require("express")();
var express = require("express");
app.use(express.static(__dirname + '/public'));
var http = require("http").Server(app);
var io = require("socket.io")(http);
app.get("/", function(req, res){
res.sendfile("index.html");
});
var mySocket;
// Obsługa portu szeregowego
var SerialPort = require("serialport").SerialPort;
var mySerial = new SerialPort("/dev/ttyUSB0", {
baudrate: 9600,
});
mySerial.on("open", function(){
console.log("Port OPEN.");
});
mySerial.on("data", function(data){
//console.log("Data: " + data + 'ls/n');
io.emit("dataArduino",{
valor: data
});
});
mySerial.on("error", function(error){
console.log("Failed to open: " + error);
});
io.on("connection", function(socket){
console.log("Socket.io polaczony.")
});
http.listen(3000, function(){
console.log("http.listen");
});
index.html
<!doctype html>
<html lang="pl">
<head>
<meta charset="utf-8">
<title>Arduino node.js test</title>
<script src="/socket.io/socket.io.js"></script>
</head>
<body>
<script type="text/javascript">
var socket = io();
socket.on("dataArduino", function(data){
console.log(data);
document.write("Data: "+ data + "<br />");
});
</script>
</body>
</html>