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

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.

Related

JS user input function

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.

netlify: WebSocket connection failed: Connection closed before receiving a handshake response

I have app on Netlify and I get some error:
server don't work: 9aeacd2….js:1 WebSocket connection to 'wss://xxxxxxxxxxxxx/:5000' failed: Connection closed before receiving a handshake response. Only start site is served.
Locally all works perfect and I wasn't getting any error. App builds on Netlify (gulp) and this is angular app.
Help me and thanks!
My server code:
"use strict";
process.title = 'node-chat';
var webSocketsServerPort = (process.env.PORT || 5000);
var webSocketServer = require('websocket').server;
var http = require('http');
var pref = '../';
var fs = require('fs');
var index = fs.readFileSync('src/index.html');
var clients = [];
var loggedUsers = [];
var tables = [];
var err;
/**
* HTTP server
*/
var server = http.createServer(function (req, res) {
var status;
var type;
var file = null;
switch (req.url) {
case "/":
case "/src/index.html":
file = index;
status = 200;
type = "text/html";
break;
default:
status = 404;
type = "text/plain";
}
res.writeHead(status, {'Content-Type': type});
if (file !== null) {
res.end(file);
} else {
res.end();
}
});
server.listen(webSocketsServerPort, function () {
console.log((new Date()) + " Server is listening on port " +
webSocketsServerPort);
});
/**
* WebSocket server
*/
var wsServer = new webSocketServer({
httpServer: server
});
wsServer.on('request', function (request) {
console.log((new Date()) + ' Connection from origin ' + request.origin +
'.' );
var connection = request.accept(null, request.origin);
var index = clients.push(connection) - 1;
connection.on('message', function (message) {
if (message.type === 'utf8') { // accept only text
var json = JSON.parse(message.utf8Data);
switch(json.type){
case 1:
break;
}
}
});
// user disconnected
connection.on('close', function (connection) {
console.log("DISCONNECTED");
});
});

Send data whit WebSockets on C# and JS

I am trying to send data from c # to js with websockets, so they look for example send an alert when activating a function from C # but I can not make a successful connection to send and receive the data, this is my code js
var ws;
var reconnectTimer;
function connect() {
ws = new WebSocket('ws://' + host + ':' + port + '/');
ws.onopen = function() {
clearInterval(reconnectTimer);
console.log('Conexión WebSockets establecida');
};
ws.onmessage = function(e) {
if (!e.data || e.data.length === 0 || e.data === '')
return;
console.log('Recibiendo: ' + e.data);
var message = JSON.parse(e.data);
if (message.Name === undefined)
return;
if (!handlers.has(message.Name))
return;
if (message.Arguments === undefined)
message.Arguments = [];
handlers.get(message.Name)(ws, message.Arguments, message);
};
ws.onclose = function() {
console.log('Conexión WebSockets no establecida, esperando reconexión');
clearInterval(reconnectTimer);
reconnectTimer = setInterval(reconnect, 3000);
};
}
function reconnect() {
console.log('Reconectando WebSockets...');
ws.close();
ws = undefined;
connect();
}
connect();
function sendMessage(handlerName, args) {
var jsonMessage = {
Name: handlerName,
Arguments: args
};
var message = JSON.stringify(jsonMessage);
console.log('Enviando: ' + message);
ws.send(message);
}
I'm using "Fleck" in C#, but I can't get it to work.

how to send files to other people in small nodejs chat app

I have made a small chat app with nodejs and now i'm trying to make it possible, if two people are chatting, that they can also send small files to each other.
I have just started learning node, so it's a bit confusing for me. I'm trying to make this work but i'm not even sure how am i supposed to do it.
So any help is welcome :)
btw var file is a file from the input type=file.
Here's my code:
index.js
var express = require("express");
var app = express();
var fs = require("fs");
var port = 8888;
// fs.readFile(sendFile, function (err, data) {
// if (err) {
// return console.error(err);
// }
// console.log("Asynchronous read: " + data.toString());
// });
app.set('views', __dirname + '/tpl');
app.set('view engine', "jade");
app.engine('jade', require('jade').__express);
app.use(express.static(__dirname + '/public'));
app.get("/", function(req, res){
res.render("page");
});
var io = require('socket.io').listen(app.listen(port));
io.sockets.on('connection', function (socket) {
socket.emit('message', { message: 'Welcome to the chat :)' });
socket.on('send', function (data) {
io.sockets.emit('message', data);
});
});
io.sockets.on('sendFile', function(data){
socket.emit('getFile',data)
});
chat.js
window.onload = function() {
var messages = [];
var socket = io.connect('http://'+location.host);
var field = document.getElementById("field");
var sendButton = document.getElementById("send");
var content = document.getElementById("content");
var name = document.getElementById("name");
var file = document.getElementById("file").files;
// file.onchange = function(e) {
// var file = document.getElementById("file").files;
// console.log(file);
// }
socket.on('message', function (data) {
if(data.message) {
messages.push(data);
var html = '';
for(var i=0; i<messages.length; i++) {
html += '<b>' + (messages[i].username ? messages[i].username : 'Server') + ': </b>';
html += messages[i].message + '<br />';
}
content.innerHTML = html;
} else {
console.log("There is a problem:", data);
}
});
socket.on('getFile', function (data) {
console.log(data);
});
sendButton.onclick = sendMessage = function() {
if(name.value == "") {
alert("Please type your name!");
} else {
socket.emit('sendFile', file);
var text = field.value;
socket.emit('send', { message: text, username: name.value });
field.value = "";
}
};
field.addEventListener("keyup", function(e){
if(e.keyCode == 13) {
sendMessage();
}
});
}
May be this is not answer using your code but you can Make it easy by using delivery module
Bidirectional File Transfers For Node.js via Socket.IO, See code on Github Link

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