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.
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 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.
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>
Here is my code
server.js
var http = require('http');
var app = require('express')();
var server = http.createServer(app).listen(process.env.PORT, process.env.IP);
var io = require('socket.io').listen(server);
var textData = "some random initial text that will be changed forever, never to be restored to its original state."
app.get('/', function(req, res){
res.sendFile(__dirname + '/index.html');
});
var users = 0;
io.on('connection', function(socket){
users++;
console.log(users + " users are here.");
//broadcast recieved data
socket.on('textChange', function(text){
textData = text;
socket.broadcast.emit('updatedText', textData);
});
socket.on("disconnect", function(){
users--;
console.log(users + " users are here.");
})
});
index.html
<!DOCTYPE html>
<html>
<head>
<script type="text/javascript" src="https://code.jquery.com/jquery-latest.min.js"></script>
<script src="/socket.io/socket.io.js"></script>
<script>
/* global io */
var socket = io();
$(document).ready(function() {
//send value on key up
$('#textarea').keyup(function(){
socket.emit('textChange', $('#textarea').val());
});
//recieve changed value
socket.on('updatedText', function(text){
$('#textarea').val(text);
});
});
</script>
<style type="text/css">
form, form * {
width: 100%;
height: 400px;
}
</style>
</head>
<body>
<h1>HELLO</h1>
<h2></h2>
<form action="">
<textarea id="textarea"></textarea>
</form>
</body>
</html>
It is working as inteded but when the two people type simultaniously, it alternates between them and just bugs out. How can I make it so that two people can type together.
I am thinking about using diff-patch but Im not sure if it will even solve this issue.
Please Help.
maybe you can add some user identifier(e.g. sessionid or uuid or other stuff) to recognize the users,etc:
// add user id
var user = Math.random();
$('#textarea').keyup(function(){
socket.emit('textChange', {name: user, val: $('#textarea').val()});
});
//recieve changed value
socket.on('updatedText', function(text){
if (text.user == user) {
$('#textarea').val(text.val);
}
});
I'm trying to make real time chat with nodeJs.. But i have some problems.
The console.log in the part of
io.on('connection', function(socket)
{
console.log("A user connected");
});
does not console.log at all.
When I got stuck i was searching for a guide.. I build it almost the same as in the guide.
Here is my html page:
<!doctype html>
<html>
<head>
<title>
Socket.IO chat
</title>
<link rel="stylesheet" href="./CSS/style.css" media="screen" title="no title" charset="utf-8">
</head>
<body>
<ul id="messages">
</ul>
<form action="">
<input id="m" autocomplete="off" />
<button>
Send
</button>
</form>
<script src="/socket.io/socket.io.js"></script>
<script>
var socket = io();
</script>
</body>
</html>
And here my js file:
var app = require("express")(),
http = require("http").Server(app),
io = require("socket.io")(http),
port = 3000;
app.get('/', function(req, res)
{
res.sendFile(__dirname + "./index.html");
});
io.on('connection', function(socket)
{
console.log("A user connected");
});
http.listen(port, function()
{
console.log('Listening on port: ' + port);
});
my file structure:
^because I think it has something to do with the linking between the pages.
I am using this guide: http://socket.io/get-started/chat/
Thanks in advance,
I hope to get some answers so i can go on with this :)
Cheers
It looks like your HTML page is missing the server URL:
var socket = io.connect("http://" + window.location.host); //e.g. http://localhost:3000