JS user input function - javascript

So i am running a online chat function using js that currently sends and receives messages and has a user count in the top right corner that updates when a user leaves or joins. I need help with making a js function that you can submit a name to and it saves it and prints it alongside your own messages.
my current code on chat.js-
var WebSocketServer = require("ws").Server;
var wss = new WebSocketServer({port:3030});
var msgArray = new Array();
wss.on("connection", function(client) {
client.on("message", function(message) {
wss.clients.forEach(function(client) {
sendChat(client, message);
});
msgArray.push(message);
});
sendChat(client, `Welcome to chat :)`);
sendUC();
msgArray.forEach(function(item) {
sendChat(client, item);
})
});
function sendChat(client, message) {
var msg = ["chat", message];
client.send(JSON.stringify(msg));
}
function sendUC(){
wss.clients.forEach(function(client){
var UCmsg = ["uc",wss.clients.size];
client.send(JSON.stringify(UCmsg));
});
}
My current code on client.js-
var ws = new WebSocket("ws://jg.codesphere.net:3030");
ws.onmessage = function (payload) {
var msg = JSON.parse(payload.data);
if (msg[0] == "chat") {
addMessage(msg[1]);
}
if (msg[0] == "uc") {
addMessage("Another user joined");
adduc(msg[1]);
}
};
$(function () {
document.forms[0].onsubmit = function () {
var input = $("input#message").val();
$("input#message").val('');
ws.send(input);
};
});
function User() {
}
function addMessage(m) {
var html = "<p>" + m + "</p>";
$("div#messages").append(html);
}
function adduc(m) {
var html = "<p>" + m + "</p>";
$("span#1").html(m + " users online");
}
So i need help with where i would call a user entry function and how to make the function.

Related

Server crash, sending message at restart (Node.js / Socket.io)

Hey guys i am doing a message system all is working fine but now i want to add the thing that if the server crash and restart the message that have been send during this time will be send at the restart of the server. I am trying to save the information of the message in the client side and make a "waiting" system that will wait to a server response. So i wanted to know how can i do that "waiting" system because now i am doing like that :
while (socket.connected === false) {
}
But that make bug the client because the infinit loop is way too fast ... so is that possible to set a timer ? (i have already tried but i dind't find how to make a good timer in a loop).
Or maybe i am totaly wrong and i haven't to do a waiting system but an other thing so tell me if my technic will not work or if there is one better :)
So here is my code :
Client.js (startTchat is called when someone is connected)
(function($){
var socket = io.connect('http://localhost:1337');
var lastmsg = [];
var me_id = [];
var friend_ = [];
var conv_ = [];
var isPlace_ = [];
var isLocation_ = [];
var me_ = [];
var my_id;
startTchat = function(user_id, username, friend_id, conv_id, isPlace, isLocalisation) {
my_id = user_id;
socket.emit('login_chat', {
id : user_id,
username : username,
friend : friend_id,
conv : conv_id,
isPlace : isPlace,
isLocalisation : isLocalisation,
})
};
/**
* Error
*/
socket.on('error', function(err){
alert(err);
});
/**
* Messages
*/
$('#chat_form').submit(function(event){
var a = 0;
while (socket.connected === false) {
}
event.preventDefault();
console.log('ME', my_id, 'TAB', me_id);
socket.emit('new_msg', {message: $('#message').val() }, me_id[my_id], friend_[my_id], conv_[my_id], isPlace_[my_id], isLocation_[my_id], me_[my_id]);
if (a === 1) {
console.log('HEYYYYYYYYYY', my_id);
}
$('#message').val('');
$('#message').focus();
});
socket.on('new_msg', function(message, me, id_receiver, id_transmiter){
if (me.id === id_receiver || me.id === id_transmiter) {
if (lastmsg != message.user.id) {
$('#new_message').append('<span class="time_date"> ' + message.h + ' : ' + message.m + ' | ' + message.y + '-' + message.m + '-' + message.d + ' | ' + message.user.username + '</span>'
+ '<p>' + message.message + '</p>\n'
);
lastmsg = message.user.id;
} else {
$('#new_message').append('<p>' + message.message + '</p>'
);
}
}
});
/**
* Login
*/
socket.on('new_user', function(user, friend, conv, isPlace, isLocation){
me_id[user.id] = user.id;
friend_[user.id] = friend;
conv_[user.id] = conv;
isPlace_[user.id] = isPlace;
me_[user.id] = user;
isLocation_[user.id] = isLocation;
$('#new_user').append('<div class="chat_list active_chat" id="' + user.id + '">\n' +
' <div class="chat_people">\n' +
' <div class="chat_img"> <img src="https://ptetutorials.com/images/user-profile.png" alt="sunil"> </div>\n' +
' <div class="chat_ib">\n' +
' <h5>' + user.username + ' <span class="chat_date">Id : ' + user.id + '</span></h5>\n' +
' </div>\n' +
' </div>\n' +
' </div>');
});
/**
* Disconnect
*/
socket.on('disc_user', function(user){
$('#' + user.id).remove();
})
})(jQuery);
And server.js :
var http = require('http');
var MongoClient = require('mongodb').MongoClient;
// Connection URL
const url = 'mongodb://localhost:27017';
// Database Name
const dbName = 'msg';
MongoClient.connect(url, function(err, client) {
if (err)
throw err;
console.log('MongoDB connected ...');
httpServer = http.createServer(function(req, res) {
console.log('This is a test');
res.end('Hello World');
});
httpServer.listen(1337);
var io = require('socket.io').listen(httpServer);
var users = {};
var messages = [];
io.sockets.on('connection', function (socket) {
const collection = client.db(dbName).collection('MessageUser');
var me = false;
var friend = false;
var conv = false;
var isPlace = false;
var room = false;
var isLocalisation = false;
for(var k in users) {
socket.emit('new_user', users[k]);
}
/**
* Login
*/
socket.on('login_chat', function (user) {
me = user;
friend = user.friend;
isPlace = user.isPlace;
conv = user.conv;
isLocalisation = user.isLocalisation;
if (isPlace === 0) {
room = user.conv;
} else {
room = user.conv + '-Place';
}
socket.join(room);
//console.log('New user : ', me.username, ' - id : ', me.id);
users[me.id] = me;
io.sockets.emit('new_user', me, friend, conv, isPlace, isLocalisation);
});
/**
* Disconnect
*/
socket.on('disconnect', function() {
if (!me) {
return false;
}
delete users[me.id];
io.sockets.emit('disc_user', me);
});
/**
* Message receive
*/
socket.on('new_msg', function(message, me_id, friend_, conv_, isPlace_, isLocalisation_, me_){
if (message.message !== '') {
message.user = me;
date = new Date();
message.h = date.getHours();
message.m = date.getMinutes();
message.y = date.getFullYear();
message.m = date.getMonth();
message.d = date.getDate();
console.log(message);
messages.push(message);
msg = {};
msg.content = message.message;
msg.sendAt = new Date();
msg.idTransmitter = me.id;
if (isPlace === 0) {
msg.idReceiver = friend;
} else {
msg.idReceiver = conv;
}
msg.idConversation = conv;
msg.isPlace = isPlace;
msg.isLocalisation = isLocalisation;
collection.insertOne(msg);
console.log('---1---', msg.idReceiver, '---2---', msg.idTransmitter, '---3---', me);
io.to(room).emit('new_msg', message, me, msg.idReceiver, msg.idTransmitter);
}
});
});
});
ps : Tell me if you need more info, sorry if i forget something that my first time using js, node and socket.io :)
while (socket.connected === false) {
}
Don't do that, it will block your page and hold your processor to 100%.
Instead, use setTimeout. It's the equivalent of sleep in javascript. You need to refactor your code to call setTimeout in a recursive fashion, and count the number of "retries" (if you want to stop at some point).
Code:
$('#chat_form').submit(function(event){
var retries = 0, max_retries = 10;
function tryNewMessage() {
if (socket.connected === false) {
if (retries >= max_retries) return; //handle max_retries properly in your code
//this is where you sleep for 1 second, waiting for the server to come online
setTimeout(tryNewMessage, 1000);
retries++;
}
else {
var a = 0;
event.preventDefault();
console.log('ME', my_id, 'TAB', me_id);
socket.emit('new_msg', {message: $('#message').val() }, me_id[my_id], friend_[my_id], conv_[my_id], isPlace_[my_id], isLocation_[my_id], me_[my_id]);
if (a === 1) {
console.log('HEYYYYYYYYYY', my_id);
}
$('#message').val('');
$('#message').focus();
}
}
tryNewMessage();
});

Opentok chat is running slowly according I execute session.disconnect() and session.connect()

I am new to the Opentok API and I am writing tests. In my tests I simulated disconnecting from the room and connecting again, but if I execute it at various times, the chat is runs slowly, until broken.
To init the chat I run $scope.initSession() and to disconnect I run $scope.disconnectFromSession().
I am using the Opentok.js version 2.13.2. See my following code:
var apiKey, sessionId, token;
apiKey = //my api key;
sessionId = //my sessionid;
token = //my token;
var session = null;
var publisher = null;
var stream = null;
var connectionCount = 0;
var publisherProperties = {frameRate: 7};
$scope.connected = false;
$scope.initSession = function() {
if (OT.checkSystemRequirements() == 1) {
// Initialize Session Object
session = OT.initSession(apiKey, sessionId);
createElement("publisher");
// initialize a publisher
publisher = OT.initPublisher('publisher', publisherProperties);
session.on({
streamCreated: function(event) {
console.log("EVENT streamCreated: " + event.stream.name + " - " + event.reason);
createElement("subscriber");
stream = event.stream;
session.subscribe(stream, 'subscriber');
},
streamDestroyed: function(event) {
event.preventDefault();
console.log("EVENT streamDestroyed: " + event.stream.name + " - " + event.reason);
console.log('Stream ${event.stream.name} ended because ${event.reason}.');
}
});
connectToSession();
} else {
console.log('Browser havenĀ“t support to WebRTC');
}
}
function connectToSession() {
session.connect(token, function(err) {
if (err) {
if (err.name === "OT_NOT_CONNECTED") {
showMessage('Failed to connect. Please check your connection and try connecting again.');
} else {
showMessage('An unknown error occurred connecting. Please try again later.');
}
} else {
// publish to the session
session.publish(publisher);
$scope.connected = true;
}
});
}
function createElement(id) {
console.log(document.getElementById(id));
if (document.getElementById(id) === null) {
var divPublisher = document.createElement("div");
divPublisher.setAttribute("id", id);
document.getElementById("div-videos").appendChild(divPublisher);
}
}
$scope.disconnectFromSession = function() {
session.disconnect();
$scope.connected = false;
OT.off();
}
$scope.initSession();
I appreciate any help.

How do I send a message ONLY to a specific socket.id?

I'm slowly setting up the structure a project and while I can ping an alert to every other user besides the ping source, I still need to be able to ping an alert to a specific user. I assume the best way to do this is to ping to a certain socket.id. Any ideas how to do this? socket.broadcast.to(socket.id) doesn't seem to work in my setup as I keep getting an error (Cannot read property 'to' of undefined).
client.js
// BROWSERIFY
//DEPENDENCIES
var P2P = require("socket.io-p2p");
var io = require("socket.io-client");
var ss = require("socket.io-stream");
var socket = io();
var opts = { autoUpgrade: true, peerOpts: { numClients: 10 } };
var p2p = new P2P(socket, opts);
var $ = require("jquery");
//Handler for the ping button
var pingRoom = function () {
socket.emit('pingAlert');
};
window.pingRoom = pingRoom;
var pingTwo = function () {
socket.emit('pingAlertTwo');
};
window.pingTwo = pingTwo;
////////////////////////////////////////////////////////
//Intercepts the pingBack event from the server side
socket.on('pingBack', function (data) {
alert("ALERT");
});
socket.on('pingBackTwo', function (data) {
socket.broadcast.to(socketid).emit('message', 'for your eyes only');
});
////////////////////////////////////////////////////////
//Peer number counter (incomplete functionality)
p2p.on("peer-num", function (num) {
console.log("You are peer number " + num);
$(".peerNum").html("You are connected to " + num + " peers.");
});
////////////////////////////////////////////////////////
//Appends stream to element
p2p.on("file", function (stream) {
//console.log(stream);
var img = document.createElement("img");
img.src = (window.URL || window.webkitURL).createObjectURL(new Blob(stream));
document.getElementById("receivedImages").appendChild(img);
});
////////////////////////////////////////////////////////
//Converts file to binary stream and logs progress in the console
$(function () {
$("#file").change(function (e) {
ss.forceBase64 = true;
var file = e.target.files[0];
var stream = ss.createStream();
ss(socket).emit("file", stream, { size: file.size, name: file.name });
var blobStream = ss.createBlobReadStream(file);
var size = 0;
blobStream.on("data", function (chunk) {
size += chunk.length;
console.log(Math.floor(size / file.size * 100) + "%");
});
blobStream.pipe(stream);
});
});
////////////////////////////////////////////////////////
//Logs users in the user log
socket.on('users_log', function (data) {
$('#log').append(data + "<br>");
console.log(data);
});
////////////////////////////////////////////////////////
server.js
//DEPENDENCIES
var app = require("express")();
var express = require("express");
var server = require("http").Server(app);
var p2pserver = require("socket.io-p2p-server").Server;
var io = require("socket.io")(server);
var ss = require("socket.io-stream");
var path = require("path");
//Added configuration
app.use(express.static(__dirname));
app.use(express.static("server_scripts"));
app.use(express.static("client_scripts"));
io.use(p2pserver);
//Peer number
var peerNum = 0;
////////////////////////////////////////////////////////
//Connections and disconnections
io.on("connection", function (socket) {
//Increments the peer number for connected peers
console.log("Peer " + peerNum + " connected");
io.emit("peer-num", peerNum);
peerNum++;
////////////////////////////////////////////////////////
//Streamer
ss(socket).on("file", function (stream, data) {
var filename = path.basename(data.name);
var parts = [];
stream.on("data", function (data) {
parts.push(data);
});
stream.on("end", function () {
socket.broadcast.emit("file", parts);
});
});
////////////////////////////////////////////////////////
//Holds the socket.id of connections
ID = socket.id;
////////////////////////////////////////////////////////
//Emits connection status to user end (User ID log)
io.sockets.emit('users_log', "client id - " + ID + " connected");
io.sockets.emit('users_online', ID);
////////////////////////////////////////////////////////
//Server side logging of connections
console.log('client id - ' + ID + ' connected.');
////////////////////////////////////////////////////////
//Alert listener and response
socket.on('pingAlert', function () {
console.log('Ping');
io.sockets.emit('pingBack');
});
socket.on('pingAlertTwo', function () {
console.log('PingTwo');
io.sockets.emit('pingBackTwo');
});
////////////////////////////////////////////////////////
//Handles disconnections
socket.on('disconnect', function () {
//Emits disconnection to user end (User ID log)
io.sockets.emit('users_log', "client id - " + ID + " disconnected");
//Decreases peer counter on disconnect
peerNum--;
////////////////////////////////////////////////////////
//Server side logging of disconnections
console.log('client id - ' + ID + ' disconnected.')
io.sockets.emit('users_offline', ID);
//NOTE: Features need to be added here
////////////////////////////////////////////////////////
})
});
//Listen on
server.listen(8000, function () {
console.log("Listening on 8000")
});
io.sockets.connected[ID].emit('ping',data);
ID is socketId, data is payload you want send with event.
when you write io.function() The Event is emitted for all users, but if you write socket.function(), the event is emitted for that particular socket.
If you wish to emit some message to a particular user, use socket.emit() function.

twilio video call error- Failed to add Participant to Conversation

Inside the main twilio account I have created two accounts so that I can establish a video call between the two. But every time I try to do so It gives me an error saying 'Failed to add Participant to Conversation twilio video chat'. But when I call any of these accounts from twilio testing tools the call is successfully connected. I dont what is the mistake I am doing here. My code is:
THIS IS MY SCRIPT:
var conversationsClient;
var activeConversation;
var previewMedia;
var identity;
var accessManager;
var localEndpoint;
var uid = document.getElementById('uid').value;
var key = document.getElementById('key').value;
if (!navigator.webkitGetUserMedia && !navigator.mozGetUserMedia) {
alert('WebRTC is not available in your browser.');
}
$.getJSON('/video/token.php?uid=' + uid + '&key=' + key, function (data) {
identity = data.identity;
accessManager = new Twilio.AccessManager(data.token);
console.log(identity);
localEndpoint = identity;
var endpointOptions = {wsServer: 'wss://' + data.sid + '.endpoint.twilio.com'};
conversationsClient = new Twilio.Conversations.Client(accessManager, endpointOptions);
conversationsClient.listen().then(clientConnected, function (error) {
log('Could not connect to Twilio: ' + error.message);
});
});
function clientConnected() {
document.getElementById('invite-controls').style.display = 'block';
log("Connected to Twilio. Listening for incoming Invites as '" + conversationsClient.identity + "'");
conversationsClient.on('invite', function (invite) {
log('Incoming invite from: ' + invite.from);
invite.accept().then(conversationStarted);
});
document.getElementById('button-invite').onclick = function () {
var inviteTo = document.getElementById('invite-to').value;
if (!inviteTo) {
alert('Enter User ID');
return false;
}
if (activeConversation) {
activeConversation.invite(inviteTo);
} else {
var options = {};
if (previewMedia) {
options.localMedia = new Twilio.Conversations.LocalMedia();
}
conversationsClient.inviteToConversation(inviteTo, options).then(conversationStarted, function (error) {
log('Unable to create conversation');
console.error('Unable to create conversation', error.message);
});
}
};
}
function conversationStarted(conversation) {
log('In an active Conversation');
activeConversation = conversation;
if (!previewMedia) {
conversation.localMedia.attach('#local-media');
}
conversation.on('participantConnected', function (participant) {
log("Participant '" + participant.identity + "' connected");
participant.media.attach('#remote-media');
});
conversation.on('participantDisconnected', function (participant) {
log("Participant '" + participant.identity + "' disconnected");
});
conversation.on('disconnected', function (conversation) {
log("Connected to Twilio. Listening for incoming Invites as '" + conversationsClient.identity + "'");
conversation.localMedia.stop();
conversation.disconnect();
activeConversation = null;
});
}
document.getElementById('button-preview').onclick = function () {
if (!previewMedia) {
previewMedia = new Twilio.Conversations.LocalMedia();
Twilio.Conversations.getUserMedia().then(
function (mediaStream) {
previewMedia.addStream(mediaStream);
previewMedia.attach('#local-media');
},
function (error) {
console.error('Unable to access local media', error);
log('Unable to access Camera and Microphone');
});
}
};
function log(message) {
document.getElementById('log-content').innerHTML = message;
}
THIS IS MY PHP FILE
$sid = "AC63406acac5aa7bd54e231ab631bc26d6";
$token = "5430f5320bae6f6099b2ab550eff13fc";
$client = new Services_Twilio($sid, $token);
$uid = $_GET['uid'];
$key = $_GET['key'];
$keyq = $client->account->keys->get($uid);
//$key = $client->account->keys->create(array("FriendlyName" => "ajay"));
//echo $key->sid.'<br>';
//echo $key->secret;
//die('');
//var_dump($client->account);exit;
// Get an object from its sid. If you do not have a sid,
// check out the list resource examples on this page
$identity = $keyq->friendly_name;
//$token = new Services_Twilio_AccessToken($sid,'SKf91ca28602e5eff8357583cb052b24f4','2kvqUiBplMieCdwwYC7ijRT8tFvzeQIt',3600,$identity);
//$token->addEndpointGrant($sid);
//$token->enableNTS();
//$grant = new Services_Twilio_Auth_ConversationsGrant();
//$grant->setConfigurationProfileSid('AC63406acac5aa7bd54e231ab631bc26d6');
////$token->addGrant($grant);
$token = new Services_Twilio_AccessToken($uid,$sid, $key);
$token->addEndpointGrant($identity);
$token->enableNTS();
echo json_encode(array(
'identity' => $identity,
'token' => $token->toJWT(),
'sid' => $sid
));
Megan from Twilio here.
First, it can be very useful to turn on debugging:
conversationsClient = new Twilio.Conversations.Client(accessManager, {logLevel: 'debug'});
And subsequently inspect the output in the console.
You might need to double check your AccessToken and make sure you're working with them correctly by following these instructions:
https://www.twilio.com/docs/api/video/guide/identity
Hope this helps!

Use TripleSec encryption with Node.js Socket.io Chat

I am new to Node.js and I've created a simple chat application using Socket.io. I am trying to encrypt the messages using the triplesec library but I am having some issues. What would be the best approach to add this encryption/decryption:
var triplesec = require('triplesec');
// Encrypt Function
triplesec.encrypt({
key: new triplesec.Buffer('secretkey'),
data: new triplesec.Buffer('secretthings'),
}, function (err, buff) {
if(!err) {
var ciphertext = buff.toString('hex')
console.log(buff.toString('hex'))
}
// Decrypt Function
triplesec.decrypt({
data: new triplesec.Buffer(ciphertext, "hex"),
key: new triplesec.Buffer('secretkey')
}, function (err, buff) {
if(!err) {
console.log(buff.toString());
}
});
});
To this client: (All encryption on the messages coming in and going out will be handled client side, assuming this is the best approach?)
// imports
var readline = require('readline');
var socketio = require('socket.io-client');
var util = require('util');
var clc = require("cli-color");
var async = require("async");
// globals
var nick;
var serverAddress;
var serverPort;
var socket;
var rl = readline.createInterface(process.stdin, process.stdout);
// message types
var chat = clc.green;
var pm = clc.yellow;
var notice = clc.cyan;
var emote = clc.blue;
var error = clc.red;
// function definitions
function consoleOut (msg) {
process.stdout.clearLine();
process.stdout.cursorTo(0);
console.log(msg);
rl.prompt(true);
}
// handle a command that the user has entered
function handleCommand (commandType, arg) {
switch (commandType) {
case 'nick': // set the nickname and send a message with the updated nickname
var notice = nick + " changed their name to " + arg;
nick = arg;
socket.emit('send', { type: 'notice', message: notice });
break;
case 'pm': // private message another user
var to = arg.match(/[a-z]+\b/)[0];
var message = arg.substr(to.length, arg.length);
socket.emit('send', { type: 'pm', message: message, to: to, from: nick });
break;
case 'me': // the user performs some emote
var emote = nick + " " + arg;
socket.emit('send', { type: 'emote', message: emote });
break;
default: // invalid command type
consoleOut(error("That is not a valid command."));
}
}
// start of execution
async.series([
function(callback) {
// get the address
rl.question("Please enter the address of the server, such as 192.168.0.10: ", function(address) {
serverAddress = address;
callback();
});
},
function(callback) {
// get the port
rl.question("Please enter the port the server is listening on, such as 8080: ", function(port) {
serverPort = port;
socket = socketio.connect('http://' + serverAddress + ':' + serverPort);
// register the sockets on message event handler
socket.on('message', function (data) {
var leader;
// process message, these are pretty self explainitory
if (data.type == 'chat' && data.nick != nick) {
leader = chat("<" + data.nick + "> ");
consoleOut(leader + data.message);
}
else if (data.type == "notice") {
consoleOut(notice(data.message));
}
else if (data.type == "pm" && data.to == nick) {
leader = pm("["+data.from+"->"+data.to+"]");
consoleOut(leader + data.message);
}
else if (data.type == "emote") {
consoleOut(emote(data.message));
}
});
callback();
});
},
function(callback) {
// get the users nickname
rl.question("Please enter a nickname: ", function(name) {
nick = name;
var msg = nick + " has joined the chat";
socket.emit('send', { type: 'notice', message: msg });
rl.prompt(true);
callback();
});
}
]);
// called when the user hits enter on the command line
// parses what ever they typed into either a command or a chat message
rl.on('line', function (line) {
if (line[0] == "/" && line.length > 1) {
var cmd = line.match(/[a-z]+\b/)[0];
var arg = line.substr(cmd.length+2, line.length);
handleCommand(cmd, arg);
rl.prompt(true);
} else {
// send chat message
socket.emit('send', { type: 'chat', message: line, nick: nick });
rl.prompt(true);
}
});

Categories

Resources