When I close anyone client, why is clearUp:Array empty? - javascript

console.log('clear arr: ' + clearnUP.join('-'));
My question is, when closing client, why is clearUp empty?
/* Beginners nodejs, fx, From China. */
var net = require('net');
var server = net.createServer();
var clients = [];
server.on('connection', function(client) {
client.write('hi\n\r');
clients.push(client);
client.on('data', function(data) {
printMsg(data, client);
});
client.on('end', function() {
clients.splice(clients.indexOf(client), 1);
});
client.on('error', function() {
console.log(err);
})
function printMsg(msg, client) {
var clearnUP = [];
for (var i = 0; i < clients.length; i++) {
client != clients[i] && (clients[i].writable ? clients[i].write(client.remotePort + ': ' + msg.toString() + '\n\r') : clearnUP.push(clients[i]) && clients[i].destroy() && clearnUP); // diswritable client push to clearUp<Array>
}
console.log(client.remotePort + ': ' + msg.toString());
console.log('clear arr: ' + clearnUP.join('-')); //when closed client, why clearUp is empty!!
}
//console.log(client);
}).listen(1220);

Related

Exported function that I intend to use in another file not working nodejs

I have a function in another file that I exported but for some reason when I call it in another file, it doesn't run.
The function I exported below;
let template = require("../templates/createModel.template.js");
const fs = require("fs");
console.log('fish')
async function createModel(formName, formFields) {
try {
let properties = [];
const newFormName = '"' + formName + '"';
let newTemplate = template;
for (let i = 0; i < formFields.length; i++) {
properties.push(
formFields[i].name + ":" + "{" + "type" + ":" + formFields[i].type + "}"
);
}
for (let j = 0; j < properties.length; j++) {
newTemplate += properties[j] + ",\n";
}
newTemplate += "},{freezeTableName: true, timestamps: false})";
newTemplate += "\n\nmodule.exports = " + formName;
newTemplate =
'const { DataTypes } = require("sequelize");' +
"\n" +
"const sequelize = require('../../db/sequelize')" +
"\n" +
"\n" +
`const ${formName} =` +
" " +
newTemplate;
newTemplate.replace("formName", formName);
fs.writeFile(
`./models/responseModels/${formName.replaceAll('"', "")}.model.js`,
newTemplate.replace("formName", newFormName),
(err) => {
if (err) {
console.log(err);
} else {
console.log("Successfully created model");
}
}
);
return;
} catch (error) {
return false;
}
}
module.exports = createModel;
The other code file in which I'm trying to make use of the function below. I required the function on the second line and named it createForm;
var amqp = require("amqplib");
const createForm = require("../../services/createForm.services");
async function createFormSheetWorker() {
const connection = await amqp.connect("amqp://localhost");
const channel = await connection.createChannel();
var queue = "createFormTaskQueue";
channel.assertQueue(queue, {
durable: true,
});
console.log(" [*] Waiting for messages in %s. To exit press CTRL+C", queue);
let message;
await channel.consume(
queue,
function (msg) {
message = JSON.parse(msg.content.toString());
console.log(message);
console.log(" [x] Received %s", message);
},
{
noAck: false,
}
);
await createForm(message);
setTimeout(function () {
console.log(" [x] Done");
connection.close();
process.exit(0);
}, 1000);
}

I want to make a private chat for every user since all the user's chat are showing in a same view

I'm trying to make a chat application using spring boot and I am stuck. This is my Frontend (custom.js) code. I want to make a separate chat view for every specific user since all user's chat which is entered in this are showing on the same view. I have given an image link in this for a better explanation if anyone could help...
custom.js
let $chatHistory;
let $button;
let $textarea;
let $chatHistoryList;
function init() {
cacheDOM();
bindEvents();
}
function bindEvents() {
$button.on('click', addMessage.bind(this));
$textarea.on('keyup', addMessageEnter.bind(this));
}
function cacheDOM() {
$chatHistory = $('.chat-history');
$button = $('#sendBtn');
$textarea = $('#message-to-send');
$chatHistoryList = $chatHistory.find('ul');
}
function render(message, userName) {
scrollToBottom();
// responses
var templateResponse = Handlebars.compile($("#message-response-template").html());
var contextResponse = {
response: message,
time: getCurrentTime(),
userName: userName
};
setTimeout(function () {
$chatHistoryList.append(templateResponse(contextResponse));
scrollToBottom();
}.bind(this), 1500);
}
function sendMessage(message) {
let username = $('#userName').val();
console.log(username)
sendMsg(username, message);
scrollToBottom();
if (message.trim() !== '') {
var template = Handlebars.compile($("#message-template").html());
var context = {
messageOutput: message,
time: getCurrentTime(),
toUserName: selectedUser
};
$chatHistoryList.append(template(context));
scrollToBottom();
$textarea.val('');
}
}
function scrollToBottom() {
$chatHistory.scrollTop($chatHistory[0].scrollHeight);
}
function getCurrentTime() {
return new Date().toLocaleTimeString().replace(/([\d]+:[\d]{2})(:[\d]{2})(.*)/, "$1$3");
}
function addMessage() {
sendMessage($textarea.val());
}
function addMessageEnter(event) {
// enter was pressed
if (event.keyCode === 13) {
addMessage();
}
}
init();
chat.js
const url = 'http://localhost:8080';
let stompClient;
let selectedUser;
let newMessages = new Map();
function connectToChat(userName) {
console.log("connecting to chat...")
let socket = new SockJS(url + '/chat');
stompClient = Stomp.over(socket);
stompClient.connect({}, function (frame) {
console.log("connected to: " + frame);
stompClient.subscribe("/topic/messages/" + userName, function (response) {
let data = JSON.parse(response.body);
if (selectedUser === data.fromLogin) {
render(data.message, data.fromLogin);
} else {
newMessages.set(data.fromLogin, data.message);
$('#userNameAppender_' + data.fromLogin).append('<span id="newMessage_' + data.fromLogin + '" style="color: red">+1</span>');
}
});
});
}
function sendMsg(from, text) {
stompClient.send("/app/chat/" + selectedUser, {}, JSON.stringify({
fromLogin: from,
message: text
}));
}
function registration() {
let userName = document.getElementById("userName").value;
$.get(url + "/registration/" + userName, function (response) {
connectToChat(userName);
}).fail(function (error) {
if (error.status === 400) {
alert("Login is already busy!")
}
})
}
function selectUser(userName) {
console.log("selecting users: " + userName);
selectedUser = userName;
let isNew = document.getElementById("newMessage_" + userName) !== null;
if (isNew) {
let element = document.getElementById("newMessage_" + userName);
element.parentNode.removeChild(element);
render(newMessages.get(userName), userName);
}
$('#selectedUserId').html('');
$('#selectedUserId').append('Chat with ' + userName);
}
function fetchAll() {
$.get(url + "/fetchAllUsers", function (response) {
let users = response;
let usersTemplateHTML = "";
for (let i = 0; i < users.length; i++) {
usersTemplateHTML = usersTemplateHTML + '<a href="#" onclick="selectUser(\'' + users[i] + '\')"><li class="clearfix">\n' +
' <img src="https://rtfm.co.ua/wp-content/plugins/all-in-one-seo-pack/images/default-user-image.png" width="55px" height="55px" alt="avatar" />\n' +
' <div class="about">\n' +
' <div id="userNameAppender_' + users[i] + '" class="name">' + users[i] + '</div>\n' +
' <div class="status">\n' +
' <i class="fa fa-circle offline"></i>\n' +
' </div>\n' +
' </div>\n' +
' </li></a>';
}
$('#usersList').html(usersTemplateHTML);
});
}

How can I use the Eclipse Paho JavaScript Client to connect to test.mosquitto.org?

I am new to the IOT world and have been confused why I have not been able to use the Eclipse Paho JavaScript Client to connect to test.mosquitto.org.
I have used Port: 8080 and Path: /mqtt as has been suggested in other paho-mqtt questions, but am met with a Failed to connect: AMQJS0007E Socket error:undefined when using this Eclipse web client.
I have used the HiveMQ WebClient and have been able to connect, publish and subscribe to both test.mosquitto.org (Port 8080) and iot.eclipse.org (Port 443).
I have noticed that HiveMQ sources mqttws31.js compared to Paho Eclipse's paho-mqtt.js, but am unsure of the significance.
I would say there are two parts to this question:
What am I missing to get the Eclipse Paho JavaScript Client to connect to test.mosquitto.org ?
What is the difference between mqttws31.js and paho-mqtt.js that allows one to connect to test.mosquitto.org relatively painlessly compared to the other?
Thanks !
Relevant Code:
The code below is taken directly from the page source of https://www.eclipse.org/paho/clients/js/utility/
paho-mqtt.js: https://www.eclipse.org/paho/js/paho-mqtt.js
utility.js (handles button callbacks):
/*******************************************************************************
* Copyright (c) 2015 IBM Corp.
*
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* and Eclipse Distribution License v1.0 which accompany this distribution.
*
* The Eclipse Public License is available at
* http://www.eclipse.org/legal/epl-v10.html
* and the Eclipse Distribution License is available at
* http://www.eclipse.org/org/documents/edl-v10.php.
*
* Contributors:
* James Sutton - Initial Contribution
*******************************************************************************/
/*
Eclipse Paho MQTT-JS Utility
This utility can be used to test the Eclipse Paho MQTT Javascript client.
*/
// Create a client instance
var client = null;
var connected = false;
logMessage("INFO", "Starting Eclipse Paho JavaScript Utility.");
// Things to do as soon as the page loads
document.getElementById("clientIdInput").value = "js-utility-" + makeid();
// called when the client connects
function onConnect(context) {
// Once a connection has been made, make a subscription and send a message.
var connectionString = context.invocationContext.host + ":" + context.invocationContext.port + context.invocationContext.path;
logMessage("INFO", "Connection Success ", "[URI: ", connectionString, ", ID: ", context.invocationContext.clientId, "]");
var statusSpan = document.getElementById("connectionStatus");
statusSpan.innerHTML = "Connected to: " + connectionString + " as " + context.invocationContext.clientId;
connected = true;
setFormEnabledState(true);
}
function onConnected(reconnect, uri) {
// Once a connection has been made, make a subscription and send a message.
logMessage("INFO", "Client Has now connected: [Reconnected: ", reconnect, ", URI: ", uri, "]");
connected = true;
}
function onFail(context) {
logMessage("ERROR", "Failed to connect. [Error Message: ", context.errorMessage, "]");
var statusSpan = document.getElementById("connectionStatus");
statusSpan.innerHTML = "Failed to connect: " + context.errorMessage;
connected = false;
setFormEnabledState(false);
}
// called when the client loses its connection
function onConnectionLost(responseObject) {
if (responseObject.errorCode !== 0) {
logMessage("INFO", "Connection Lost. [Error Message: ", responseObject.errorMessage, "]");
}
connected = false;
}
// called when a message arrives
function onMessageArrived(message) {
logMessage("INFO", "Message Recieved: [Topic: ", message.destinationName, ", Payload: ", message.payloadString, ", QoS: ", message.qos, ", Retained: ", message.retained, ", Duplicate: ", message.duplicate, "]");
var messageTime = new Date().toISOString();
// Insert into History Table
var table = document.getElementById("incomingMessageTable").getElementsByTagName("tbody")[0];
var row = table.insertRow(0);
row.insertCell(0).innerHTML = message.destinationName;
row.insertCell(1).innerHTML = safeTagsRegex(message.payloadString);
row.insertCell(2).innerHTML = messageTime;
row.insertCell(3).innerHTML = message.qos;
if (!document.getElementById(message.destinationName)) {
var lastMessageTable = document.getElementById("lastMessageTable").getElementsByTagName("tbody")[0];
var newlastMessageRow = lastMessageTable.insertRow(0);
newlastMessageRow.id = message.destinationName;
newlastMessageRow.insertCell(0).innerHTML = message.destinationName;
newlastMessageRow.insertCell(1).innerHTML = safeTagsRegex(message.payloadString);
newlastMessageRow.insertCell(2).innerHTML = messageTime;
newlastMessageRow.insertCell(3).innerHTML = message.qos;
} else {
// Update Last Message Table
var lastMessageRow = document.getElementById(message.destinationName);
lastMessageRow.id = message.destinationName;
lastMessageRow.cells[0].innerHTML = message.destinationName;
lastMessageRow.cells[1].innerHTML = safeTagsRegex(message.payloadString);
lastMessageRow.cells[2].innerHTML = messageTime;
lastMessageRow.cells[3].innerHTML = message.qos;
}
}
function connectionToggle() {
if (connected) {
disconnect();
} else {
connect();
}
}
function connect() {
var hostname = document.getElementById("hostInput").value;
var port = document.getElementById("portInput").value;
var clientId = document.getElementById("clientIdInput").value;
var path = document.getElementById("pathInput").value;
var user = document.getElementById("userInput").value;
var pass = document.getElementById("passInput").value;
var keepAlive = Number(document.getElementById("keepAliveInput").value);
var timeout = Number(document.getElementById("timeoutInput").value);
var tls = document.getElementById("tlsInput").checked;
var automaticReconnect = document.getElementById("automaticReconnectInput").checked;
var cleanSession = document.getElementById("cleanSessionInput").checked;
var lastWillTopic = document.getElementById("lwtInput").value;
var lastWillQos = Number(document.getElementById("lwQosInput").value);
var lastWillRetain = document.getElementById("lwRetainInput").checked;
var lastWillMessageVal = document.getElementById("lwMInput").value;
if (path.length > 0) {
client = new Paho.Client(hostname, Number(port), path, clientId);
} else {
client = new Paho.Client(hostname, Number(port), clientId);
}
logMessage("INFO", "Connecting to Server: [Host: ", hostname, ", Port: ", port, ", Path: ", client.path, ", ID: ", clientId, "]");
// set callback handlers
client.onConnectionLost = onConnectionLost;
client.onMessageArrived = onMessageArrived;
client.onConnected = onConnected;
var options = {
invocationContext: { host: hostname, port: port, path: client.path, clientId: clientId },
timeout: timeout,
keepAliveInterval: keepAlive,
cleanSession: cleanSession,
useSSL: tls,
reconnect: automaticReconnect,
onSuccess: onConnect,
onFailure: onFail
};
if (user.length > 0) {
options.userName = user;
}
if (pass.length > 0) {
options.password = pass;
}
if (lastWillTopic.length > 0) {
var lastWillMessage = new Paho.Message(lastWillMessageVal);
lastWillMessage.destinationName = lastWillTopic;
lastWillMessage.qos = lastWillQos;
lastWillMessage.retained = lastWillRetain;
options.willMessage = lastWillMessage;
}
// connect the client
client.connect(options);
var statusSpan = document.getElementById("connectionStatus");
statusSpan.innerHTML = "Connecting...";
}
function disconnect() {
logMessage("INFO", "Disconnecting from Server.");
client.disconnect();
var statusSpan = document.getElementById("connectionStatus");
statusSpan.innerHTML = "Connection - Disconnected.";
connected = false;
setFormEnabledState(false);
}
// Sets various form controls to either enabled or disabled
function setFormEnabledState(enabled) {
// Connection Panel Elements
if (enabled) {
document.getElementById("clientConnectButton").innerHTML = "Disconnect";
} else {
document.getElementById("clientConnectButton").innerHTML = "Connect";
}
document.getElementById("hostInput").disabled = enabled;
document.getElementById("portInput").disabled = enabled;
document.getElementById("clientIdInput").disabled = enabled;
document.getElementById("pathInput").disabled = enabled;
document.getElementById("userInput").disabled = enabled;
document.getElementById("passInput").disabled = enabled;
document.getElementById("keepAliveInput").disabled = enabled;
document.getElementById("timeoutInput").disabled = enabled;
document.getElementById("tlsInput").disabled = enabled;
document.getElementById("automaticReconnectInput").disabled = enabled;
document.getElementById("cleanSessionInput").disabled = enabled;
document.getElementById("lwtInput").disabled = enabled;
document.getElementById("lwQosInput").disabled = enabled;
document.getElementById("lwRetainInput").disabled = enabled;
document.getElementById("lwMInput").disabled = enabled;
// Publish Panel Elements
document.getElementById("publishTopicInput").disabled = !enabled;
document.getElementById("publishQosInput").disabled = !enabled;
document.getElementById("publishMessageInput").disabled = !enabled;
document.getElementById("publishButton").disabled = !enabled;
document.getElementById("publishRetainInput").disabled = !enabled;
// Subscription Panel Elements
document.getElementById("subscribeTopicInput").disabled = !enabled;
document.getElementById("subscribeQosInput").disabled = !enabled;
document.getElementById("subscribeButton").disabled = !enabled;
document.getElementById("unsubscribeButton").disabled = !enabled;
}
function publish() {
var topic = document.getElementById("publishTopicInput").value;
var qos = document.getElementById("publishQosInput").value;
var message = document.getElementById("publishMessageInput").value;
var retain = document.getElementById("publishRetainInput").checked;
logMessage("INFO", "Publishing Message: [Topic: ", topic, ", Payload: ", message, ", QoS: ", qos, ", Retain: ", retain, "]");
message = new Paho.Message(message);
message.destinationName = topic;
message.qos = Number(qos);
message.retained = retain;
client.send(message);
}
function subscribe() {
var topic = document.getElementById("subscribeTopicInput").value;
var qos = document.getElementById("subscribeQosInput").value;
logMessage("INFO", "Subscribing to: [Topic: ", topic, ", QoS: ", qos, "]");
client.subscribe(topic, { qos: Number(qos) });
}
function unsubscribe() {
var topic = document.getElementById("subscribeTopicInput").value;
logMessage("INFO", "Unsubscribing: [Topic: ", topic, "]");
client.unsubscribe(topic, {
onSuccess: unsubscribeSuccess,
onFailure: unsubscribeFailure,
invocationContext: { topic: topic }
});
}
function unsubscribeSuccess(context) {
logMessage("INFO", "Unsubscribed. [Topic: ", context.invocationContext.topic, "]");
}
function unsubscribeFailure(context) {
logMessage("ERROR", "Failed to unsubscribe. [Topic: ", context.invocationContext.topic, ", Error: ", context.errorMessage, "]");
}
function clearHistory() {
var table = document.getElementById("incomingMessageTable");
//or use : var table = document.all.tableid;
for (var i = table.rows.length - 1; i > 0; i--) {
table.deleteRow(i);
}
}
// Just in case someone sends html
function safeTagsRegex(str) {
return str.replace(/&/g, "&").replace(/</g, "<").
replace(/>/g, ">");
}
function makeid() {
var text = "";
var possible = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789";
for (var i = 0; i < 5; i++)
text += possible.charAt(Math.floor(Math.random() * possible.length));
return text;
}
function logMessage(type, ...content) {
var consolePre = document.getElementById("consolePre");
var date = new Date();
var timeString = date.toUTCString();
var logMessage = timeString + " - " + type + " - " + content.join("");
consolePre.innerHTML += logMessage + "\n";
if (type === "INFO") {
console.info(logMessage);
} else if (type === "ERROR") {
console.error(logMessage);
} else {
console.log(logMessage);
}
}
The code below is taken directly from the page source of http://www.hivemq.com/demos/websocket-client/
mqttws31.js: http://www.hivemq.com/demos/websocket-client/js/mqttws31.js
app.js (handles app callbacks):
/**
* Copyright 2013 dc-square GmbH
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* #author: Christoph Schäbel
*/
var websocketclient = {
'client': null,
'lastMessageId': 1,
'lastSubId': 1,
'subscriptions': [],
'messages': [],
'connected': false,
'connect': function () {
var host = $('#urlInput').val();
var port = parseInt($('#portInput').val(), 10);
var clientId = $('#clientIdInput').val();
var username = $('#userInput').val();
var password = $('#pwInput').val();
var keepAlive = parseInt($('#keepAliveInput').val());
var cleanSession = $('#cleanSessionInput').is(':checked');
var lwTopic = $('#lwTopicInput').val();
var lwQos = parseInt($('#lwQosInput').val());
var lwRetain = $('#LWRInput').is(':checked');
var lwMessage = $('#LWMInput').val();
var ssl = $('#sslInput').is(':checked');
this.client = new Messaging.Client(host, port, clientId);
this.client.onConnectionLost = this.onConnectionLost;
this.client.onMessageArrived = this.onMessageArrived;
var options = {
timeout: 3,
keepAliveInterval: keepAlive,
cleanSession: cleanSession,
useSSL: ssl,
onSuccess: this.onConnect,
onFailure: this.onFail
};
if (username.length > 0) {
options.userName = username;
}
if (password.length > 0) {
options.password = password;
}
if (lwTopic.length > 0) {
var willmsg = new Messaging.Message(lwMessage);
willmsg.qos = lwQos;
willmsg.destinationName = lwTopic;
willmsg.retained = lwRetain;
options.willMessage = willmsg;
}
this.client.connect(options);
},
'onConnect': function () {
websocketclient.connected = true;
console.log("connected");
var body = $('body').addClass('connected').removeClass('notconnected').removeClass('connectionbroke');
websocketclient.render.hide('conni');
websocketclient.render.show('publish');
websocketclient.render.show('sub');
websocketclient.render.show('messages');
},
'onFail': function (message) {
websocketclient.connected = false;
console.log("error: " + message.errorMessage);
websocketclient.render.showError('Connect failed: ' + message.errorMessage);
},
'onConnectionLost': function (responseObject) {
websocketclient.connected = false;
if (responseObject.errorCode !== 0) {
console.log("onConnectionLost:" + responseObject.errorMessage);
}
$('body.connected').removeClass('connected').addClass('notconnected').addClass('connectionbroke');
websocketclient.render.show('conni');
websocketclient.render.hide('publish');
websocketclient.render.hide('sub');
websocketclient.render.hide('messages');
//Cleanup messages
websocketclient.messages = [];
websocketclient.render.clearMessages();
//Cleanup subscriptions
websocketclient.subscriptions = [];
websocketclient.render.clearSubscriptions();
},
'onMessageArrived': function (message) {
// console.log("onMessageArrived:" + message.payloadString + " qos: " + message.qos);
var subscription = websocketclient.getSubscriptionForTopic(message.destinationName);
var messageObj = {
'topic': message.destinationName,
'retained': message.retained,
'qos': message.qos,
'payload': message.payloadString,
'timestamp': moment(),
'subscriptionId': subscription.id,
'color': websocketclient.getColorForSubscription(subscription.id)
};
console.log(messageObj);
messageObj.id = websocketclient.render.message(messageObj);
websocketclient.messages.push(messageObj);
},
'disconnect': function () {
this.client.disconnect();
},
'publish': function (topic, payload, qos, retain) {
if (!websocketclient.connected) {
websocketclient.render.showError("Not connected");
return false;
}
var message = new Messaging.Message(payload);
message.destinationName = topic;
message.qos = qos;
message.retained = retain;
this.client.send(message);
},
'subscribe': function (topic, qosNr, color) {
if (!websocketclient.connected) {
websocketclient.render.showError("Not connected");
return false;
}
if (topic.length < 1) {
websocketclient.render.showError("Topic cannot be empty");
return false;
}
if (_.find(this.subscriptions, { 'topic': topic })) {
websocketclient.render.showError('You are already subscribed to this topic');
return false;
}
this.client.subscribe(topic, {qos: qosNr});
if (color.length < 1) {
color = '999999';
}
var subscription = {'topic': topic, 'qos': qosNr, 'color': color};
subscription.id = websocketclient.render.subscription(subscription);
this.subscriptions.push(subscription);
return true;
},
'unsubscribe': function (id) {
var subs = _.find(websocketclient.subscriptions, {'id': id});
this.client.unsubscribe(subs.topic);
websocketclient.subscriptions = _.filter(websocketclient.subscriptions, function (item) {
return item.id != id;
});
websocketclient.render.removeSubscriptionsMessages(id);
},
'deleteSubscription': function (id) {
var elem = $("#sub" + id);
if (confirm('Are you sure ?')) {
elem.remove();
this.unsubscribe(id);
}
},
'getRandomColor': function () {
var r = (Math.round(Math.random() * 255)).toString(16);
var g = (Math.round(Math.random() * 255)).toString(16);
var b = (Math.round(Math.random() * 255)).toString(16);
return r + g + b;
},
'getSubscriptionForTopic': function (topic) {
var i;
for (i = 0; i < this.subscriptions.length; i++) {
if (this.compareTopics(topic, this.subscriptions[i].topic)) {
return this.subscriptions[i];
}
}
return false;
},
'getColorForPublishTopic': function (topic) {
var id = this.getSubscriptionForTopic(topic);
return this.getColorForSubscription(id);
},
'getColorForSubscription': function (id) {
try {
if (!id) {
return '99999';
}
var sub = _.find(this.subscriptions, { 'id': id });
if (!sub) {
return '999999';
} else {
return sub.color;
}
} catch (e) {
return '999999';
}
},
'compareTopics': function (topic, subTopic) {
var pattern = subTopic.replace("+", "(.*?)").replace("#", "(.*)");
var regex = new RegExp("^" + pattern + "$");
return regex.test(topic);
},
'render': {
'showError': function (message) {
alert(message);
},
'messages': function () {
websocketclient.render.clearMessages();
_.forEach(websocketclient.messages, function (message) {
message.id = websocketclient.render.message(message);
});
},
'message': function (message) {
var largest = websocketclient.lastMessageId++;
var html = '<li class="messLine id="' + largest + '">' +
' <div class="row large-12 mess' + largest + '" style="border-left: solid 10px #' + message.color + '; ">' +
' <div class="large-12 columns messageText">' +
' <div class="large-3 columns date">' + message.timestamp.format("YYYY-MM-DD HH:mm:ss") + '</div>' +
' <div class="large-5 columns topicM truncate" id="topicM' + largest + '" title="' + Encoder.htmlEncode(message.topic, 0) + '">Topic: ' + Encoder.htmlEncode(message.topic) + '</div>' +
' <div class="large-2 columns qos">Qos: ' + message.qos + '</div>' +
' <div class="large-2 columns retain">';
if (message.retained) {
html += 'Retained';
}
html += ' </div>' +
' <div class="large-12 columns message break-words">' + Encoder.htmlEncode(message.payload) + '</div>' +
' </div>' +
' </div>' +
'</li>';
$("#messEdit").prepend(html);
return largest;
},
'subscriptions': function () {
websocketclient.render.clearSubscriptions();
_.forEach(websocketclient.subscriptions, function (subs) {
subs.id = websocketclient.render.subscription(subs);
});
},
'subscription': function (subscription) {
var largest = websocketclient.lastSubId++;
$("#innerEdit").append(
'<li class="subLine" id="sub' + largest + '">' +
' <div class="row large-12 subs' + largest + '" style="border-left: solid 10px #' + subscription.color + '; background-color: #ffffff">' +
' <div class="large-12 columns subText">' +
' <div class="large-1 columns right closer">' +
' x' +
' </div>' +
' <div class="qos">Qos: ' + subscription.qos + '</div>' +
' <div class="topic truncate" id="topic' + largest + '" title="' + Encoder.htmlEncode(subscription.topic, 0) + '">' + Encoder.htmlEncode(subscription.topic) + '</div>' +
' </div>' +
' </div>' +
'</li>');
return largest;
},
'toggleAll': function () {
websocketclient.render.toggle('conni');
websocketclient.render.toggle('publish');
websocketclient.render.toggle('messages');
websocketclient.render.toggle('sub');
},
'toggle': function (name) {
$('.' + name + 'Arrow').toggleClass("closed");
$('.' + name + 'Top').toggleClass("closed");
var elem = $('#' + name + 'Main');
elem.slideToggle();
},
'hide': function (name) {
$('.' + name + 'Arrow').addClass("closed");
$('.' + name + 'Top').addClass("closed");
var elem = $('#' + name + 'Main');
elem.slideUp();
},
'show': function (name) {
$('.' + name + 'Arrow').removeClass("closed");
$('.' + name + 'Top').removeClass("closed");
var elem = $('#' + name + 'Main');
elem.slideDown();
},
'removeSubscriptionsMessages': function (id) {
websocketclient.messages = _.filter(websocketclient.messages, function (item) {
return item.subscriptionId != id;
});
websocketclient.render.messages();
},
'clearMessages': function () {
$("#messEdit").empty();
},
'clearSubscriptions': function () {
$("#innerEdit").empty();
}
}
};
I think I am a bit late...but I leave here for posterity.
The Paho JS library has undergo a series of changes before release 1.0.3 and the last one 1.1.0.
If you refer to a mqttws31.js probably you was using a version earlier than 1.0.3, because from 1.0.3 the main js file was renamed to paho-mqtt.js.
Can be the reason why something in your code was working differently from HiveMQ version.
I tried to sum the situation here

beaglebone black not receiving serial bonescript

Beaglebone black - not receiving data on serial. I have connected Tx and Rx pins of the serial ports 1 and 2 directly (tx - rx). I'm kind of new to beaglebone. I used this code to send data on the serial to another device, it worked properly for transmission, but not for Rx.
I haven't found the file ttyO1, just ttyO2.
var b = require('bonescript');
var rxport = '/dev/ttyO1';
var txport = '/dev/ttyO2';
var options = { baudrate: 115200, parity: 'even', parser:
b.serialParsers.readline('\n') };
var teststring = "This is the string I'm sending out as a test";
b.serialOpen(rxport, options, onRxSerial);
function onRxSerial(x) {
console.log('rx.eventrx= ' + x.event);
if(x.err) throw('***FAIL*** ' + JSON.stringify(x));
if(x.event == 'open') {
//readReapeatedly();
b.serialOpen(txport, options, onTxSerial);
}
if(x.event == 'data') {
console.log("I am receiving on rxport");
console.log('rx (' + x.data.length +
') = ' + x.data.toString('ascii'));
}
}
function onTxSerial(x) {
console.log('tx.event = ' + x.event);
if(x.err) throw('***FAIL*** ' + JSON.stringify(x));
if(x.event == 'open') {
writeRepeatedly();
}
if(x.event == 'data') {
console.log('tx (' + x.data.length +
') = ' + x.data.toString('ascii'));
console.log(x.data);
}
}
function printJSON(x) {
console.log(JSON.stringify(x));
}
function writeRepeatedly() {
console.log("write to serial");
b.serialWrite(txport, teststring, onSerialWrite);
console.log("I have sent data");
}
function onSerialWrite(x) {
console.log("Iam in the onSerialWrite function");
if(x.err) console.log('onSerialWrite err = ' + x.err);
if(x.event == 'callback') {setTimeout(writeRepeatedly, 5000);
console.log("HERE");
}
}

simple connection error socket.io

I have a simple tcp connection server in nodejs + socket.io can send data to the server but I have no comeback.
excuse my english I'm from Brazil
see the code.
client code:
if(newY !== ymouse || newX !== xmouse)
{
socket.emit('chat', {playerX: playerX, playerY: playerY});
}
socket.on('chat',
function (data)
{
console.log(data)
// $("p#data_recieved").append("<br />\r\n [position] {" + data.msgr + ": playerX = " + data.playerX + ", playerY = " + data.playerY + "}");
document.getElementById("vy").innerHTML = data.X;
document.getElementById("vx").innerHTML = data.y;
}
server code:
var io = require('socket.io').listen(8000);
io.sockets.on('connection',
function (socket)
{
socket.on('chat',
function (data)
{
var sender = 'unregistered';
socket.get('nickname',
function (err, name)
{
console.log('Chat message by ', name);
console.log('error ', err);
console.log('X: ' + data.playerX);
console.log('Y: ' + data.playerY);
sender = name;
});
socket.broadcast.emit('chat', { playerX : data.playerX, playerY : data.playerY, msg : data, msgr : sender});
});
socket.on('position',
function (data)
{
var sender = 'unregistered';
socket.get('nickname',
function (err, name)
{
sender = name;
});
if(sender == 'unregistered')
return;
var playerX = data.playerX;
var playerY = data.playerY;
socket.broadcast.emit('position', {msgr : sender, playerX : playerX, playerY : data.playerY});
});
socket.on('register',
function (name)
{
socket.set('nickname', name,
function ()
{
io.sockets.emit('chat', {msg : "naay nag apil2! si " + name + '!', msgr : "mr. server"});
});
});
});
how can you see I can
  send data to the server but
  no response
server seems to work well
I leave an example of a simple connection in which you can inspire
Server:
var simple = io
.sockets
.on('connection', function(socket) {
socket.on('message', function(data) {
socket.broadcast.send(data);
});
socket.on('disconnect', function() {
// handle disconnect
});
});
Client:
var socket = io.connect();
var content = $('#simple-content');
socket.on('connect', function() {
$('#simple-form').css('display', 'block');
content.append($('<p>').text('Connected'));
});
socket.on('message', function(msg) {
content.append($('<p>').text(msg)
.append($('<em>').text(' from server')));
});
$('#simple-form').submit(function(e) {
e.preventDefault();
var textObj = $('#simple-text');
var msg = textObj.val();
textObj.val('');
content.append($('<p>').text(msg)
.append($('<em>').text(' from me')));
socket.send(msg);
});
I hope it will be helpful!

Categories

Resources