How to emit a message to the sockets from an API endpoint? - javascript

I have socket.io set up and working and now I need to send updates to the users via the same sockets, the updates I get from a different server (the other server makes a GET http request to my nodejs server and I need to take the data from that http request and emit it to a certain user via sockets)
Here's my code, emitting sockets from inside the socket process works fine but from inside the API call doen't work.
var express = require("express");
var app = express();
var http = require("http").createServer(app);
var io = require("socket.io")(http);
app.set('socketIo', io);
io.on("connection", (socket) => {
console.log("User connected: ", socket.id);
io.to(socket.id).emit("new_message", {id: "999", msg: "You are connected, your Id is " + socket.id});
})
app.get("/send/:id/:message", (request, result) => {
const ioEmitter = request.app.get("socketIo");
ioEmitter.to(request.params.id).emit({ id: "999", msg: request.params.message });
result.send("Sending message to socket Id: " + request.params.id)
console.log("Sending message to socket Id: " + request.params.id);
})
const port = 3001;
http.listen(port, () => {
console.log("Listening to port " + port);
});

Related

Using passport for socket.io

Hi im trying to use passport for authencication, But im not sure what to do on the client side. I think the server side is fine, but it gives me this error:failed: WebSocket is closed before the connection is established. So it seems like it cant get the connection. what do i need to send from the client side, and do i need to change something on server side??
please heeeelp thanks:)
server.js
var express = require('express');
var app = express();
var server = require('http').createServer(app);
var io = require("socket.io")(server, {
cors: {
origin: "*",
methods: ["GET", "POST"]
}
});
var port = process.env.PORT || 4000;
const passportSocketIo = require('passport.socketio')
const cookieParser = require('cookie-parser')
const session = require("express-session")
const passport = require('passport')
io.use(passportSocketIo.authorize({
cookieParser: cookieParser,
key: 'express.sid',
secret: 'session_secret',
store: session,
success: onAuthorizeSuccess,
fail: onAuthorizeFail,
}));
function onAuthorizeSuccess(data, accept){
console.log('successful connection to socket.io');
// The accept-callback still allows us to decide whether to
// accept the connection or not.
accept(null, true);
// OR
// If you use socket.io#1.X the callback looks different
accept();
}
function onAuthorizeFail(data, message, error, accept){
if(error)
throw new Error(message);
console.log('failed connection to socket.io:', message);
// We use this callback to log all of our failed connections.
accept(null, false);
// OR
// If you use socket.io#1.X the callback looks different
// If you don't want to accept the connection
if(error)
accept(new Error(message));
// this error will be sent to the user as a special error-package
// see: http://socket.io/docs/client-api/#socket > error-object
}
io.on('connection', function (socket) {
console.log("connection")
var addedUser = false;
// when the client emits 'new message', this listens and executes
socket.on('new message', function (data) {
var data = validator.escape(data);
// we tell the client to execute 'new message'
socket.broadcast.emit('new message', {
username: socket.username,
message: data
});
db.serialize(function() {
// console.log('inserting message to database');
var insertMessageStr = "INSERT INTO messages (username, content, posted) VALUES ('" + socket.username + "','" + data.toString() + "'," + Date.now() + ");"
// console.log(insertMessageStr)
db.run(insertMessageStr);
});
});
client.js
const socket = io({
key: 'express.sid',
secret: 'session_secret',
});

How to have a persistent connection with Net in Node.js?

I am using a Telnet - client to validate the emails, I connect to the server and it responds with 250 but when I write another command and ask for the answer, it simply does not answer me.
This is my code:
function ConnectTelnet(){
//var connection = new telnet();
var response;
var HOST = 'mail.dominio.com';
var PORT = 25;
var net = require('net');
var client = net.connect(25,'mail.dominio.com',function(){
console.log('connected to server!');
console.log('CONNECTED TO: ' + HOST + ':' + PORT);
client.on('data', function(data) {
console.log('Received: ' + data);
response = data;
if(response.indexOf("220") === -1){
client.write('EHLO dominio.com')
console.log(data)
}
});
})
}
Does anyone know how I can continue? Thanks :)
You can't send the data, get an answer and then send more data on the same connection. TCP does not send messages "separately". TCP is a stream protocol, which means that when you write bytes to the socket, you get the same bytes in the same order at the receiving end. There is no notion of "message boundaries" or "packets" anything of the sort.
If you want to do that, you need to make a new connection every time.
This is how I did to send several EHLO on the same connection:
const net = require('net');
const client = net.createConnection({ host: '127.0.0.1', port: 1025 }, () => {
console.log('connected to server!');
checkEHLO(client, [ 'xxx#xxx.xxx', 'xxx#xxx.xxx', 'xxx#xxx.xxx' ]);
});
client.on('data', (data) => {
console.log(data.toString());
client.end();
});
client.on('end', () => {
console.log('disconnected from server');
});
function checkEHLO(client, emails){
emails.forEach((email) => {
client.write('EHLO ' + email + '\n');
});
}
And this was the response I got:
connected to server!
220 127.0.0.1 ESMTP Service Ready
250-Hello xxx#xxx.xxx
250-PIPELINING
250-8BITMIME
250-STARTTLS
250 AUTH PLAIN LOGIN
250-Hello xxx#xxx.xxx
250-PIPELINING
250-8BITMIME
250-STARTTLS
250 AUTH PLAIN LOGIN
250-Hello xxx#xxx.xxx
250-PIPELINING
250-8BITMIME
250-STARTTLS
250 AUTH LOGIN PLAIN

TLS to multiple clients and different messages

I am planning a security system based on tcp. I want to secure it with TLS/SSL. I want to make a Client make a message to the server, the server has to check it and send to all the other clients a message back.
I think it is unclear how to handle that, because the documentation of node.js tls only shows how you connect to the server and get a message back.
This is the code of the documentation:
const tls = require('tls');
const fs = require('fs');
const options = {
key: fs.readFileSync('server-key.pem'),
cert: fs.readFileSync('server-cert.pem'),
rejectUnauthorized: true,
};
const server = tls.createServer(options, (socket) => {
console.log('server connected',
socket.authorized ? 'authorized' : 'unauthorized');
socket.write('welcome!\n');
socket.setEncoding('utf8');
socket.pipe(socket);
});
server.listen(8000, () => {
console.log('server bound');
});
Maybe you could make an example, because its totally unclear to me. Thanks for your help. If my question is unclear to you, please let me know.
'use strict';
var tls = require('tls');
var fs = require('fs');
const PORT = 1337;
const HOST = '127.0.0.1'
var options = {
key: fs.readFileSync('private-key.pem'),
cert: fs.readFileSync('public-cert.pem')
};
var users= [];
var server = tls.createServer(options, function(socket) {
users.push(socket)
socket.on('data', function(data) {
for(var i = 0; i < users.length; i++){
if(users[i]!=socket){
users[i].write("I am the server sending you a message.");
}
}
console.log('Received: %s [it is %d bytes long]',
data.toString().replace(/(\n)/gm,""),
data.length); });
});
server.listen(PORT, HOST, function() {
console.log("I'm listening at %s, on port %s", HOST, PORT);
});
server.on('error', function(error) {
console.error(error);
server.destroy();
});

Create Chat Room Using socket.io in ionic3 and angular4

I am developing Chat App Using socket.io. Problem is that when creating a room, socket-id is added to the room and then MSG is sent to the room. The first MSG is sent to room perfectly but the second MSG is not sent to the room. The second MSG is shown on the server side.
Server Side Code
var app = require('express')();
var http = require('http').Server(app);
var io = require('socket.io')(http);
io.on('connection', function(socket) {
console.log('A user connected');
socket.on('subscribe', function(room) {
var romSocketId = room.sid;
socket.to(romSocketId).join(room.roomName);
// roome = room;
console.log('user joined room ' + room);
});
socket.on('chatmessage',function(data1){
console.log(data1.msg);
console.log(data1.room);
socket.broadcast.to(data1.room).emit('msgFromSever', {message: data1.msg});
});
socket.on("msgToClient", function(data) {
var sidd = data.sid;
console.log(sidd);
// sending to individual socketid (private message)
socket.to(sidd).emit('msgFromSever', {message: data.msg, socket_id: socket.id, adminID: data.adminLoginId});
})
socket.on('disconnect', function () {
console.log('A user disconnected');
});
});
http.listen(3000, function() {
console.log('Serve Start');
});
Client Side code for Joining Room
this.socket.emit('subscribe', {roomName:'room' +this.joinRoomNummber, sid : socketid});
Client Side code to Send Msg
this.socket.emit('chatmessage', {msg: this.input.msg, room: this.randomId});

Run client socket.io on terminal

I was searching a if there is a way to run a node.js & socket.io client on terminal. My goal its that both client & server run on terminal. It work in a webpage but no in a terminal, any ideas?
terminal based chat application using socket.io and readline
Server :
var app = require('express')();
var http = require('http').createServer(app);
var io = require('socket.io')(http);
io.on('connection', (socket) => {
console.log('a user connected');
socket.on('disconnect', () => {
console.log('user disconnected');
});
let eventName = 'simple chat message';
let broadcast = (msg) => socket.broadcast.emit(eventName, msg);
socket.on(eventName, (msg, ackFn) => {
console.log('message: ' + msg);
// broadcast to other clients after 1.5 seconds
setTimeout(broadcast, 1500, msg);
});
});
http.listen(3000, () => {
console.log('listening on *:3000');
});
Server opens connection on http://localhost:3000
Receive messages from client and broadcast to other client
Client :
const io = require("socket.io-client");
const readline = require('readline');
const rl = readline.createInterface({ input: process.stdin, output: process.stdout });
rl.question('What\'s your name ? ', (name) => {
const socket = io('http://localhost:3000');
const sendMsg = () => {
rl.question('> ', (reply) => {
console.log(`Sending message: ${reply}`);
socket.emit('simple chat message', `${name} says ${reply}`);
sendMsg();
});
}
socket.on('connect', () => {
console.log('Sucessfully connected to server.');
sendMsg();
});
socket.on('simple chat message', (message) => {
console.log(message);
});
socket.on('disconnect', () => {
console.log('Connection lost...')
});
});
Read text from terminal using rl.question()and send it to server using socket.emit()
send msg() is called recursively to read text from terminal and send it to server
socket.on() is used to receive messages from other clients
Simple use socket.io-client from node process
https://github.com/socketio/socket.io-client
You could use PhantomJS to run a headless browser on the terminal and have JavaScript for socket.io client in the page loaded to PhantomJS.

Categories