i have a problem in this code (anyway sorry for my short Eng.)
i think this is a right code but don't know why it makes errors about indentation? any solutions or advices for this code :( ??
u can ignore the Korean that i wrote in this code
- if (!isSuccess)
script
alert('cannot make a chat room.');
location.href = '/enter';
- else
h3 room title :
span#roomName= roomName
input#leave(type='button', value='나가기')
#chatWindow(style='width:400px; height:400px; overflow:auto; border:1px solid #000; float:left; margin-right:10px;')
div(style='width:100px; height:400px; overflow:auto; border:1px solid #000;')
p 참가자
ul#attendants
each attendant in attendants
li(id='attendant-'+attendant)= attendant
form
span#myName #{nickName}
input(type='text', style='width:300px;')#message
input(type='submit', value='보내기')
script(type='text/javascript')
$(document).ready(function() {
var room = io.connect('/room');
var chatWindow = $('#chatWindow');
var messageBox = $('#message');
var myName = $('#myName').text();
var attendants = $('#attendants');
var showMessage = function(msg) {
chatWindow.append($('<p>').text(msg));
chatWindow.scrollTop(chatWindow.height());
};
room.on('connect', function() {
room.emit('join', {roomName:$('#roomName').text(), nickName:myName});
});
room.on('joined', function(data) {
if(data.isSuccess) {
showMessage(data.nickName + '님이 입장하셨습니다.');
attendants.append($('<li>')
.attr('id', 'attendant-'+data.nickName)
.text(data.nickName));
}
});
room.on('message', function(data) {
showMessage(data.nickName + ' : ' + data.msg);
});
room.on('leaved', function(data) {
showMessage(data.nickName + '님이 나가셨습니다.');
$('#attendant-'+data.nickName).remove();
});
$('form').submit(function(e) {
e.preventDefault();
var msg = messageBox.val();
if ($.trim(msg) !== '') {
showMessage(myName + ' : ' + msg);
room.json.send({nickName:myName, msg:msg});
messageBox.val('');
}
});
$('#leave').click(function(e) {
room.emit('leave', {nickName:myName});
location.href='/enter';
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.7.0/jquery.min.js"></script>
If you want to add multiple lines/blocks when you're writing inline JS/CSS you need to add a .
script.
alert('cannot make a chat room.');
location.href = '/enter';
script(type='text/javascript').
$(document).ready(function() {
var room = io.connect('/room');
Related
I'm trying to get my phone's orientation data to send to a local server via node's WebSocket (ws) library. In my research, it seems that orientation data is only accessible using ssl, so this will only work if I have a wss/https. I've got a node server working with a self-signed certificate, and it works fine on a desktop browser, but when I run it on my iphone, I end up getting an error message when it tries to connect. Code below, any suggestions/alternatives are greatly appreciated! (I'm more of a graphics/multimedia programmer, so certain web/server terms could be lost on me)
client.js:
let socket = new WebSocket("wss://192.168.0.10:3000");
socket.onopen = function(e) {
alert("[open] Connection established ");
alert("Sending to server");
socket.send("Hello");
};
socket.onmessage = function(event) {
alert(`[message] Data received from server: ${event.data}`);
};
socket.onclose = function(event) {
if (event.wasClean) {
alert(`[close] Connection closed cleanly, code=${event.code} reason=${event.reason}`);
} else {
// e.g. server process killed or network down
// event.code is usually 1006 in this case
alert('[close] Connection died');
}
};
socket.onerror = function(error) {
alert(`[error] ${error.message}`);
};
function showCoords(event) {
var x = event.clientX;
var y = event.clientY;
var coords = "X coords: " + x + ", Y coords: " + y;
console.log(coords);
socket.send(coords);
}
server.js:
var express = require('express');
var app = express();
const https = require('https');
const fs = require('fs');
// var cors = require('cors');
const options = {
key: fs.readFileSync('key.pem'),
cert: fs.readFileSync('cert.pem')
};
const WebSocket = require('ws');
// var server = app.listen(3000);
const server = https.createServer(options, app);
const wss = new WebSocket.Server({ server });
wss.on('connection', function connection(ws) {
ws.on('message', function message(msg) {
console.log("WS connect "+msg);
});
});
app.use(express.static('public'));
console.log('socket server is running');
server.listen(3000, function () {
console.log('Example app listening on port 3000! Go to https://localhost:3000/')
console.log('')
const ws = new WebSocket(`wss://localhost:${server.address().port}`, {
rejectUnauthorized: false
});
ws.on('open', function open() {
ws.send('All glory to WebSockets! '+server.address().port);
});
})
function newConnection(socket) {
console.log(socket.id);
socket.on('mouse', mouseMsg);
function mouseMsg(data){
socket.broadcast.emit('mouse', data);
console.log(data);
}
}
index.html
<!DOCTYPE html>
<html lang="">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<style type="text/css">
.garden {
position: relative;
width : 200px;
height: 200px;
border: 5px solid #CCC;
border-radius: 10px;
}
.ball {
position: absolute;
top : 90px;
left : 90px;
width : 20px;
height: 20px;
background: green;
border-radius: 100%;
}
</style>
<title>Detecting device orientation - Orientation_example - code sample</title>
<script src="sketch.js"></script>
</head>
<body>
<main>
<div onclick="showCoords(event)" class="garden">
<div class="ball"></div>
</div>
<pre class="output"></pre>
<script>
var ball = document.querySelector('.ball');
var garden = document.querySelector('.garden');
var output = document.querySelector('.output');
var maxX = garden.clientWidth - ball.clientWidth;
var maxY = garden.clientHeight - ball.clientHeight;
function handleOrientation(event) {
var x = event.alpha; // In degree in the range [-180,180]
var y = event.beta; // In degree in the range [-90,90]
output.innerHTML = "beta : " + y + "\n";
// output.innerHTML += "gamma: " + y + "\n";
// Because we don't want to have the device upside down
// We constrain the x value to the range [-90,90]
if (x > 90) { x = 90};
if (x < -90) { x = -90};
// To make computation easier we shift the range of
// x and y to [0,180]
x += 90;
y += 90;
// 10 is half the size of the ball
// It center the positioning point to the center of the ball
ball.style.top = (maxY*y/180 - 10) + "px";
ball.style.left = (maxX*x/180 - 10) + "px";
}
window.addEventListener('deviceorientation', handleOrientation);
</script>
</main>
</body>
</html>
You should be able to do this with https://ngrok.com/. Once you install ngrok (you will need a free account). Run your server and client. Point ngrok to your client local port i.e. 8000 ~/ngrok http 8000 copy the returned https url i.e. https://xxxxxxxx.ngrok.io on your device.
I want my extension to open up in the form of an iframe instead of the normal popup window. I've been able to achieve this so far. Now I'm trying to make this iframe draggable using jQuery UI but unable to do so. My code for inject.js is as below:
function toggleVisisbility (node) {
node.style.display = (node.style.display === 'none' || node.style.display === '') ? 'block' : 'none'
}
function appendIframe(app) {
var iframe = document.createElement('iframe');
iframe.id = 'popup-app';
iframe.style.cssText = 'position:absolute;top:0;right:0;display:block;' +
'width:350px;height:500px;z-index:99999999;' +
'border: none;' +
'box-shadow: 0px 8px 16px rgba(0,0,0,0.25);';
chrome.storage.local.get("logged_in", function(data) {
if(data.logged_in) {
iframe.src = chrome.runtime.getURL('./html/loggedPopup.html')
} else {
iframe.src = chrome.runtime.getURL('./html/popup.html')
}
});
app.appendChild(iframe)
}
function insertIframe(anchor) {
let app = Array.from(anchor.childNodes).find(function(node){ return node.id === 'popup-app'})
if (app) {
if (app.querySelectorAll('iframe').length === 0) {
appendIframe(app)
}
toggleVisisbility(app)
} else {
appendIframe(anchor)
}
}
var extensionOrigin = 'chrome-extension://' + chrome.runtime.id
if (!location.ancestorOrigins.contains(extensionOrigin)) {
var anchor = document.getElementById('cfp-anchor')
if (anchor) {
insertIframe(anchor)
} else {
const AppRoot = document.createElement('div', { id: 'cfp-anchor' });
AppRoot.id = 'cfp-anchor';
const body = document.getElementsByTagName('body')[0];
body.appendChild(AppRoot);
AppRoot.innerHTML = '';
insertIframe(AppRoot)
}
}
I figured out the solution. I used a div instead of an iframe, made the div draggable and then loaded my html inside the div. I used the following code:
function appendIframe(app) {
var draggableDiv = document.createElement('div');
draggableDiv.id = 'popup-app';
draggableDiv.className = 'draggable';
draggableDiv.setAttribute('data-draggable', 'true');
draggableDiv.style.cssText = 'position:fixed;top:16px;right:21px;display:block;' +
'width:350px;height:500px;z-index:99999999;' +
'border: none; cursor: move;' +
'box-shadow: 0px 8px 16px rgba(0,0,0,0.25);' +
'background: #25BAF1;';
chrome.storage.local.get("logged_in", function(data) {
if(data.logged_in) {
document.getElementById("popup-app").innerHTML='<object id="overlay" style="width: 100%; height: 100%; position: absolute; top: 25px" type="text/html" data='+chrome.runtime.getURL('./html/loggedPopup.html')+' ></object>';
} else {
document.getElementById("popup-app").innerHTML='<object id="overlay" style="width: 100%; height: 100%; position: absolute; top: 25px" type="text/html" data='+chrome.runtime.getURL('./html/popup.html')+' ></object>';
}
});
$("#popup-app").addClass(".draggable");
makeDivDraggable();
app.appendChild(draggableDiv)
}
function makeDivDraggable(){
$(document).ready(function() {
var $body = $('body');
var $target = null;
var isDraggEnabled = false;
$body.on("mousedown", "div", function(e) {
$this = $(this);
isDraggEnabled = $this.data("draggable");
if (isDraggEnabled) {
if(e.offsetX===undefined){
x = e.pageX-$(this).offset().left;
y = e.pageY-$(this).offset().top;
}else{
x = e.offsetX;
y = e.offsetY;
}
$this.addClass('draggable');
$body.addClass('noselect');
$target = $(e.target);
}
});
$body.on("mouseup", function(e) {
$target = null;
$body.find(".draggable").removeClass('draggable');
$body.removeClass('noselect');
});
$body.on("mousemove", function(e) {
if ($target) {
$target.offset({
top: e.pageY - y,
left: e.pageX - x
});
}
});
});
}
What this basically does is create a div, which is draggable and then sticks up another layer of html on top. The modified position allows to grab the div from the top and then move it around.
I am new to the NodeJs. I have created a simple application using socket.io. I know that I can use ExpressJs framework but I am not getting overall idea as to how to separate the code and divide them into multiple pages so that debugging and maintenance is easily.
I am not understanding how to structure the code and where to write the socket.io code or any other NodeJs code in general.
Should I create new folder and files? If yes then how?
My code: app.js
var app = require('express')();
var server = require('http').createServer(app);
var io = require('socket.io').listen(server);
var ent = require('ent');
var fs = require('fs');
var cntActiveProductSupport = 0;
var cntActiveCustomer = 0;
var support_socket_id = '';
app.get('/',function (req, res) {
res.sendFile(__dirname+'/index.html');
});
app.get('/product_support',function (req, res) {
res.sendFile(__dirname+'/admin.html');
});
io.sockets.on('connection',function(socket,username){
//Each Socket in Socket.IO is identified by a random, unguessable, unique identifier Socket#id
console.log(socket.id);
//total number of connections
console.log(io.engine.clientsCount);
socket.on('support_connected',function(username){
username = ent.encode(username);
socket.username = username;
socket.broadcast.emit('support_connected',username);
//get socket id of all connected sockets
Object.keys(io.sockets.sockets).forEach(function(id) {
console.log("ID:",id) // socketId
});
cntActiveProductSupport++;
support_socket_id = socket.id;
});
socket.on('new_client',function(username){
var client_socket_id = socket.id;
username = ent.encode(username);
socket.username = username;
socket.broadcast.emit('new_client',{ username: username, socket_id: socket.id, support_socket_id: support_socket_id });
socket.to(client_socket_id).emit('client_connected',{ username: username, support_socket_id: support_socket_id });
cntActiveCustomer++;
});
socket.on('message',function(data){
//socket.disconnect(true); use this if you want to disconnect client from server
//client which sent the message
var client_socket_id = socket.id;
var message = ent.encode(data.message);
// sending to individual socketid (private message)
//socket.to(socketId).emit('hey', 'I just met you');
socket.to(support_socket_id).emit('message', {username: socket.username,message:message, client_socket_id: client_socket_id});
});
socket.on('support_messaging',function(data){
message = ent.encode(data.message);
var customer_socket_id = data.customer_socket_id;
//socket.broadcast.emit('message', {username: socket.username,message:message});
// sending to individual socketid (private message)
socket.broadcast.to(customer_socket_id).emit('message', {username: socket.username,message:message});
//socket.to(socketId).emit('hey', 'I just met you');
//It's the same command as for rooms, that's because:
//"For your convenience, each socket automatically joins a room identified by this id."
});
socket.on('typing',function(username){
socket.broadcast.emit('typing', username);
});
socket.on('stopped-typing',function(){
socket.broadcast.emit('stopped-typing');
});
});
server.listen(8080);
My code: index.html
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
<title>Real-time Super Chat!</title>
<style>
#zone_chat strong {
color: white;
background-color: black;
padding: 2px;
}
#writeup {
font-size:9px;
color: gray;
margin: 5px 0px;
}
</style>
</head>
<body>
<h4>Real-time Super Chat!</h4>
<form action="/" method="post" id="chat_form" autocomplete="off">
<input type="text" name="message" id="message" placeholder="Your message..." size="50" />
<input type="submit" id="send_message" value="Send" />
<input type="hidden" id="support_socket_id" value=""/>
<div id="writeup"></div>
</form>
<section id="chat_zone">
</section>
<script
src="https://code.jquery.com/jquery-3.3.1.js"
integrity="sha256-2Kok7MbOyxpgUVvAk/HJ2jigOSYS2auK4Pfzbm7uH60="
crossorigin="anonymous"></script>
<script src="/socket.io/socket.io.js"></script>
<script>
// Connecting to socket.io
var socket = io.connect('http://localhost:8080');
var socketConnected = false;
// The username is requested, sent to the server and displayed in the title
var username = prompt('What\'s your username?');
//var username = 'Deepak';
socket.emit('new_client', username);
document.title = username + ' - ' + document.title;
socket.on('connect', function() {
socketConnected = true;
console.log('Connected! ID: ' + socket.id);
});
socket.on('client_connected', function(data){
$('#support_socket_id').val(data.support_socket_id);
});
socket.on('disconnect', function() {
socketConnected = false;
console.log('Disconnected!');
});
// When a message is received it's inserted in the page
socket.on('message', function(data) {
insertMessage(data.username, data.message)
});
// When a new client connects, the information is displayed
// socket.on('new_client', function(username) {
// $('#chat_zone').prepend('<p><em>' + username + ' has joined the chat!</em></p>');
// });
socket.on('typing',function(username){
$('#writeup').html(username + ' is typing...');
});
socket.on('stopped-typing',function(){
$('#writeup').html('');
});
$(document).ready(function () {
$('#message').on('focus',function(){
socket.emit('typing',username);
});
$('#message').on('blur',function(){
socket.emit('stopped-typing',username);
});
// When the form is sent, the message is sent and displayed on the page
$('#chat_form').submit(function () {
var message = $('#message').val();
var support_socket_id = $('#support_socket_id').val();
socket.emit('message', { message:message, support_socket_id:support_socket_id }); // Sends the message to the others
insertMessage(username, message); // Also displays the message on our page
$('#message').val('').focus(); // Empties the chat form and puts the focus back on it
return false; // Blocks 'classic' sending of the form
});
});
// Adds a message to the page
function insertMessage(username, message) {
$('#chat_zone').prepend('<p><strong>' + username + '</strong> ' + message + '</p>');
}
</script>
</body>
</html>
You should create node modules in order to maintain the code structure. For example create routes folder and put all the route in there and separate them like users.js is a route file to cater routing related to user. As you are using socket.io you can create a separate module for socket.io functions and use them in your routes.
This link might help you: https://nodejs.org/api/modules.html
I hope it helps.
App Structure: routes, enter image description here
How do I create rectangles with 4 ports (each side) in a correct way, so I can save and restore them via JSON?
I tried this one, but only the rectangles are been saved. The connections and labels got lost.
JSFiddle: http://jsfiddle.net/xfvf4/36/
Create two elements (Add) - move them and connect them
Write: This gives the content as JSON-Array
Read: Should make the grafic out of the JSON-Array
The last point doesn't work.
JS:
var LabelRectangle = draw2d.shape.basic.Rectangle.extend({
NAME: "draw2d.shape.basic.Rectangle",
init: function (attr) {
this._super(attr);
this.label = new draw2d.shape.basic.Label({
text: "Text",
fontColor: "#0d0d0d",
stroke: 0
});
this.add(this.label, new draw2d.layout.locator.CenterLocator(this));
this.label.installEditor(new draw2d.ui.LabelInplaceEditor());
this.createPort("hybrid", new draw2d.layout.locator.BottomLocator(this));
},
getPersistentAttributes: function () {
var memento = this._super();
memento.labels = [];
var ports = [];
ports = this.getPorts();
memento.ports = [];
console.log(ports);
this.children.each(function (i, e) {
console.log(e);
memento.labels.push({
id: e.figure.getId(),
label: e.figure.getText(),
locator: e.locator.NAME
});
ports.each(function (i, e) {
memento.ports.push({
//id: e.id,
name: e.name,
locator: e.locator.NAME
});
});
});
return memento;
},
setPersistentAttributes: function (memento) {
this._super(memento);
this.resetChildren();
$.each(memento.labels, $.proxy(function (i, e) {
var label = new draw2d.shape.basic.Label(e.label);
var locator = eval("new " + e.locator + "()");
locator.setParent(this);
this.add(label, locator);
}, this));
}
});
$(window).load(function () {
var canvas = new draw2d.Canvas("gfx_holder");
$("#add").click(function (e) { // Add a new rectangle
var rect = new LabelRectangle({
width: 200,
height: 40,
radius: 3,
bgColor: '#ffffff',
stroke: 0
});
rect.createPort("hybrid", new draw2d.layout.locator.OutputPortLocator(rect));
rect.createPort("hybrid", new draw2d.layout.locator.InputPortLocator(rect));
rect.createPort("hybrid", new draw2d.layout.locator.TopLocator(rect));
canvas.add(rect, 150, 200);
});
$("#write").click(function (e) { // Write to pre-Element (JSON)
var writer = new draw2d.io.json.Writer();
writer.marshal(canvas, function(json){
$("#json").text(JSON.stringify(json,null,2));
$('#gfx_holder').empty();
});
});
$("#read").click(function (e) { // Read from pre-Element (JSON)
var canvas = new draw2d.Canvas("gfx_holder");
var jsonDocument = $('#json').text();
var reader = new draw2d.io.json.Reader();
reader.unmarshal(canvas, jsonDocument);
});
});
HTML:
<ul class="toolbar">
<li>Add</li>
<li>Write</li>
<li>Read</li>
</ul>
<div id="container" class="boxed">
<div onselectstart="javascript:/*IE8 hack*/return false" id="gfx_holder" style="width:100%; height:100%; ">
</div>
<pre id="json" style="overflow:auto;position:absolute; top:10px; right:10px; width:350; height:500;background:white;border:1px solid gray">
</pre>
</div>
Just use the write.js and Reader.js in the "json"-Folder of Draw2D.js 5.0.4 and this code:
$(window).load(function () {
var canvas = new draw2d.Canvas("gfx_holder");
// unmarshal the JSON document into the canvas
// (load)
var reader = new draw2d.io.json.Reader();
reader.unmarshal(canvas, jsonDocument);
// display the JSON document in the preview DIV
//
displayJSON(canvas);
// add an event listener to the Canvas for change notifications.
// We just dump the current canvas document into the DIV
//
canvas.getCommandStack().addEventListener(function(e){
if(e.isPostChangeEvent()){
displayJSON(canvas);
}
});
});
function displayJSON(canvas){
var writer = new draw2d.io.json.Writer();
writer.marshal(canvas,function(json){
$("#json").text(JSON.stringify(json, null, 2));
});
}
This should work:
var LabelRectangle = draw2d.shape.basic.Rectangle.extend({
NAME: "draw2d.shape.basic.Rectangle",
init: function (attr) {
this._super(attr);
this.label = new draw2d.shape.basic.Label({
text: "Text",
fontColor: "#0d0d0d",
stroke: 0
});
this.add(this.label, new draw2d.layout.locator.CenterLocator(this));
this.label.installEditor(new draw2d.ui.LabelInplaceEditor());
},
getPersistentAttributes: function () {
var memento = this._super();
memento.labels = [];
memento.ports = [];
this.getPorts().each(function(i,port){
memento.ports.push({
name : port.getName(),
port : port.NAME,
locator: port.getLocator().NAME
});
});
this.children.each(function (i, e) {
memento.labels.push({
id: e.figure.getId(),
label: e.figure.getText(),
locator: e.locator.NAME
});
});
return memento;
},
setPersistentAttributes: function (memento) {
this._super(memento);
this.resetChildren();
if(typeof memento.ports !=="undefined"){
this.resetPorts();
$.each(memento.ports, $.proxy(function(i,e){
var port = eval("new "+e.port+"()");
var locator = eval("new "+e.locator+"()");
this.add(port, locator);
port.setName(e.name);
},this));
}
$.each(memento.labels, $.proxy(function (i, e) {
var label = new draw2d.shape.basic.Label(e.label);
var locator = eval("new " + e.locator + "()");
locator.setParent(this);
this.add(label, locator);
}, this));
}
});
I thought the whole point of socket.io was to not have to worry about modern browsers? lol
Anyway, I am new to socket programming. I have a small app that simply mimics mouse movements.
You open several browsers and when you move the mouse, your actions are recorded in the other browsers. It moves a small square. Kinda cool. However, when I open it on my iPad (iOS6) nothing! Sockets isn't connecting. I even put an alert message in the connect event and nothing.
Works in IE, FF and Chrome just fine on my laptop. The only difference is that my dev machine uses localhost while the iPad uses my machine's IP. However, when I connect to my local IP on my laptop, it still works. Just not in Safari/iPad.
Here is my server.
var app = require('http').createServer(handler),
io = require('socket.io').listen(app),
fs = require('fs');
app.listen(80);
function handler(req, res) {
var file = __dirname + '/public/index.html';
fs.readFile(file,
function(err, data) {
if(err) {
res.writeHead(500);
return res.end('Error loading index.html');
}
res.writeHead(200);
res.end(data);
}
);
}
var rooms = ['abc', 'test1'];
var sockets = [];
io.sockets.on('connection', function(socket) {
sockets.push(socket);
socket.on('m', function(data) {
socket.broadcast.to(socket.room).emit('relay', {msg: 'MouseX: ' + data.x + ' MouseY: ' + data.y, x: data.x, y: data.y});
});
socket.on('join', function(room) {
socket.join(room);
socket.emit('updateStatus', {msg: 'Joined room ' + room});
console.log('Joined room ' + room);
});
});
Here is my client:
<!doctype html>
<html>
<head>
<style>
body {
padding: 40px;
}
#cursor {
background:white;
border:1px solid black;
color: white;
display: block;
height:24px;
padding:6px;
position:absolute;
width:24px;
z-index:20;
}
</style>
</head>
<body>
<input id='msg' type='text' size='100' /><br />
<input id='box' type='text' size='100' />
<div id='cursor'></div>
<script src='/socket.io/lib/socket.io.js'></script>
<script>
var socket = io.connect('http://localhost');
var b = document.getElementById('box');
var m = document.getElementById('msg');
var c = document.getElementById('cursor');
// join custom room
socket.on('connect', function() {
socket.emit('join', 'abc');
});
// update status messages from server
socket.on('updateStatus', function(data) {
m.setAttribute('value', data.msg);
});
socket.on('relay', function(data) {
b.setAttribute('value', data.msg);
c.style.left = parseInt(data.x) + 'px';
c.style.top = parseInt(data.y) + 'px';
});
document.onmousemove = function(event) {
event = event || window.event;
socket.emit('m', {x: event.clientX, y: event.clientY});
}
</script>
</body>
</html>
Localhost is local to the machine. You're IP should use a ip address or domain name:
something like:
io.connect('192.168.1.110');
or io.connect('test.myapp.com');