Angular won't showing my array result in HTML - javascript

I got problem with my angular ... I currently working for a simple chat broadcast with socket io, but why my array object won't show up in html after socket io catch the emit
Here's my code for index.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title></title>
</head>
<body ng-app='BaseModule'>
<div ng-controller="ChatController">
<input type='number' name='sender' ng-model='sender' />
<input type='number' name='to' ng-model='to' />
<textarea name='message' ng-model='message'></textarea>
<button type='button' ng-click='sendMessage()'>send it</button>
<pre>{{ conversation }}</pre>
</div>
</body>
<script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/socket.io/1.7.3/socket.io.js"></script>
<script type="text/javascript" src="angular.min.js"></script>
<script type="text/javascript" src="base.js"></script>
<script></script>
</html>
and here's the code for my base.js
var app = angular.module('BaseModule', []);
app.run(function($rootScope) {
});
app.controller('ChatController', ChatController);
function ChatController($scope){
var self = window.location.hostname;
var socket = io.connect('http://' + self + ':8890');
$scope.to = '';
$scope.message = '';
$scope.conversation = [];
socket.on('connect', function () {
$scope.sendMessage = function(){
var message = {
to: $scope.to,
sender: $scope.sender,
message: $scope.message
};
socket.emit('chat', message);
};
});
socket.on('broadcast', function(data){
$scope.conversation = data;
console.log($scope.conversation);
});
}
and this is my gulpfile.js
var gulp = require('gulp');
gulp.task('socketio', function(){
var app = require('express')();
var server = require('http').Server(app);
var io = require('socket.io')(server);
var conversations = [];
server.listen(8890);
io.on('connection', function (socket) {
socket.on('chat', function(data){
conversations.push(data);
console.log(conversations);
socket.emit('broadcast', conversations);
});
});
});
as you can see I was running my socket io via gulp, it's worked actually, but the problem is with $scope.conversation in my index.html, why won't it change ?

It might be an issue with $scope binding, so try by adding the $scope.$digest(); after the $scope.conversation = data;

Related

Sending var over socket.io

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>

getting error in <script src = "/socket.io/socket.io.js"></script>

i know this question has been asked many times buit i have spent 3 hours trying to figure it out but to no avail. i am getting error in GET
http://localhost:3000/socket.io/socket.io.js net::ERR_ABORTED
and io is not defined. any help would be highly appreciated. i am typing extra coz my post requires more details ..........
public/index.html
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<title>Page Title</title>
<meta name="viewport" content="width=device-width, initial-scale=1">
<link rel="stylesheet" type="text/css" media="screen" href="styles.css" />
</head>
<body>
<div id="wrapper">
<div class="form_div" id ="login">
<p class="form_label">LOGIN FORM</p>
<form method="post" action="">
<p><input id ="user-name" type="text" placeholder="Enter user-name"></p>
<p><input id = "pass-word" type="password" placeholder="**********"></p>
<p><input id = "submit" type="submit" value="LOGIN"></p>
</form>
</div>
<br>
<br>
<br>
<div class="form_div" id = "signup">
<p class="form_label">SIGNUP FORM</p>
<form method="post" action="">
<p><input id ="signupusername" type="text" placeholder="Enter
Name"></p>
<p><input id = "signuppass" type="password"
placeholder="**********"></p>
<p><input id ="register" type="submit" value="SIGNUP"></p>
</form>
</div>
</div>
<script src = "index.js"></script>
<script src = "/socket.io/socket.io.js"></script>
public/index.js
var socket = io();
var loginDiv = document.getElementById('login');
var Username = document.getElementById('user-name');
var loginPassword = document.getElementById('pass-word');
var login = document.getElementById('submit');
var SignUpDiv = document.getElementById('signup');
var Signupuser = document.getElementById('signupusername');
var Signuppass = document.getElementById('signuppass');
var signup = document.getElementById('register');
login.onclick = function(){
socket.emit('login-details',{
username:Username.value,
password:loginPassword.value
});
}
signup.onclick = function(){
socket.emit('signup-details',{
newuser:Signupuser.value,
newuserpassword:Signuppass.val
});
}
socket.on('login-response',(data)=>{
if(data.success){
alert('login Successful');
}
else{
alert('login Unsuccessful');
}
});
socket.on('signup-response',(data)=>{
if(data.success){
alert('Signup Successful')
}
else{
alert('Signup-Successful')
}
});
server/server.js
var express = require('express');
var path = require('path');
var http = require('http');
var MongoClient = require('mongodb').MongoClient;
const socketIO = require('socket.io');
var app = express();
var server = http.createServer(app);
const port = process.env.PORT ||3000;
var io = socketIO(server);
const pathjoin = path.join( __dirname ,'../public');
app.use(express.static(pathjoin));
MongoClient.connect('mongodb://localhost:27017/DETAILS',(err,client)=>{
if(err){
return console.log('unable to connect to the MongoDb server');
}
const db =client.db('DETAILS');
console.log('connected to the MongoDb server');
});
io.on('connection',(socket)=>{
console.log('new user connected');
//login
socket.on('login-details',(data)=>{
db.collection('user-
details').find({username:data.username,password:data.password},
(err,result)=>{
if(err) throw err;
socket.emit('login-response',{
success:true
});
});
});
//signup
socket.on('signup-details',(data)=>{
db.collection('user-
details').insert({username:data.newuser,password:data.newuserpassword},
(err,result)=>{
if(err) throw err;
socket.emit('signup-response',{
success:true
});
});
});
});
app.listen(port,()=>{
console.log('server started');
});
In your server/server.js, at the very end of your codes, change app.listen() to server.listen(), because express requires that you instantiate a HTTP server in Socket.IO.
This should be your new ending part of server.js
server.listen(port,()=>{
console.log('server started');
});
In index.html
<script src = "index.js"></script>
<script src = "/socket.io/socket.io.js"></script>
change it to
<script src = "/socket.io/socket.io.js"></script>
<script src = "index.js"></script>
Swap the includes in html .First you need to include socket.io and then use it in index.js.
In index.js
var socket = io.connect();
error solved. It was a silly mistake! since socket.io uses http server and not the express server. so i did create a http server but at during listening to a port i use express like app.listen(). In server/server.js it should be:
server.listen(port,()=>{ console.log('server started');});
Try this. Change,
<script src = "/socket.io/socket.io.js"></script>
to
<script src="http://YOUR_IP_ADDRESS/socket.io/socket.io.js"></script>

socket io not giving the desired output

I have created a index.js which loads index.html using sockets.
the server is running successfully and also the index.html page loads. but cant append the written text in the div.
index.js
var express = require('express'),
app = express(),
server = require('http').createServer(app),
io = require('socket.io').listen(server);
server.listen(3000, function() {
console.log("SERVER CREATED WITH PORT 3000");
});
app.get('/', function(req, res) {
res.sendfile(__dirname + '/index.html');
});
io.sockets.on('connection', function(socket) {
socket.on('send', function(data) {
io.sockets.emit('new', data);
});
});
index.html
<html>
<head>
<title>chat</title>
<style>
#chat {
height: 500px;
}
</style>
</head>
<body>
<div id="chat"></div>
<form id="send-message">
<input id="message" />
<input type="submit" />
</form>
<h1>Working</h1>
<script src="jquery-3.2.1.min.js"></script>
<script src="/socket.io/socket.io.js"></script>
<script>
jQuery(function($) {
var socket = io.connect();
var $messageform = $('#send-message');
var $messagebox = $('#message');
var $chat = $('#chat');
$messageform.submit(function(e) {
e.preventDefault();
socket.emit('send', $messagebox.val());
$messagebox.val('');
});
socket.on('new', function(data) {
$chat.append(data + "<br />");
});
});
</script>
</body>
</html>
These are the files which I have created and want to send the text to all tabs.
The browser just gets refreshed without loading the text when submit is hit.
Please let me know what I am doing wrong.

Get data by socket.io in html page

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>

socket.io rich text editing with Quill

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.

Categories