Create Chat Room Using socket.io in ionic3 and angular4 - javascript

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});

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 emit a message to the sockets from an API endpoint?

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);
});

ng-websocket and ws: client sends successfully but doesn't receive

My angularjs client websocketserver can properly send to the server, but when sending from server to client, the client doesn't register the event.
I'm using angular-websockets at the client side and ws at my express.js server
Here's my code.
server
var port = process.env.PORT || 3002;
var server = http.createServer(app); // app = express
server.listen(port);
var socketComs = require('./lib/socketcoms').connect(server);
var connect = function(server) {
var wss = new WebSocketServer({
server: server
});
wss.on('connection', function(ws) {
console.log("websocket connection open");
ws.on('message', function incoming(message) {
console.log('received', message); // THIS WORKS FINE
});
var id = setInterval(function() {
ws.send('pong', 'data 123', function(err) {
console.log('sent pong', err); // THIS IS NEVER CAUGHT BY CLIENT, err = clean
});
}, 2000); // Pong is never received
});
};
client
var connect = function() {
ws.$on('$open', function() {
console.log('wow its working');
ws.$emit('message', 'some message');
});
ws.$on('pong', function(data) {
console.log('yes', data);
});
ws.$on('$close', function(data) {
console.log('wss closed');
});
};
Can anyone see what's going wrong?
I'm using ng-websocket with PHP socket, and I have the same issue.
I just opened the ng-websocket.js and..guess what? the "ping" and "pong" events don't exist!
The "incoming" event is called "$message"...
This is how to get data from server:
ws.$on('$message', function (response) {
console.log("DATA FROM SERVER", response);

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.

How to know when channel is subscribed/unsubscribed with socket.io

Just searched all the web to find how can I track inside node.js server when a channel is subscribed or unsubscribed. What I can do right know is the connect and disconnect bindings, but no clue how to do it with channels.
io.sockets.on('connection', function (socket) {
console.log("["+socket.id+"] Connected");
// handler to know when a socket subscribed a channel (*) ?
// handler to know when a socket unsubscribed a channel (*) ?
socket.on('disconnect', function () {
console.log("["+socket.id+"] Disconnect");
});
});
Is it possible?
You are looking for "socket.of('channelName')" ...
See Socket.io docs
SERVER:
var io = require('socket.io').listen(80);
var chat = io
.of('/chat')
.on('connection', function (socket) {
socket.emit('a message', {
that: 'only'
, '/chat': 'will get'
});
chat.emit('a message', {
everyone: 'in'
, '/chat': 'will get'
});
});
var news = io
.of('/news')
.on('connection', function (socket) {
socket.emit('item', { news: 'item' });
});
CLIENT:
<script>
var chat = io.connect('http://localhost/chat')
, news = io.connect('http://localhost/news');
chat.on('connect', function () {
chat.emit('hi!');
});
news.on('news', function () {
news.emit('woot');
});
</script>

Categories