Last active
August 17, 2018 10:47
-
-
Save jyotendra/dad2d3f90c552d2246c1023b5a599b8d to your computer and use it in GitHub Desktop.
socket connection with middleware in node and angular
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
constructor() { | |
this.chats = []; | |
this.socket = io.connect( | |
baseUrl, | |
{ | |
path: "/chat", | |
query: { "access-token": "---=====" }, | |
reconnection: false | |
} | |
); | |
this.chats.push({ | |
sent_by: this.sentByType.bot, | |
message: "hi", | |
time: new Date() | |
}); | |
this.chats.push({ | |
sent_by: this.sentByType.user, | |
message: "hello", | |
time: new Date() | |
}); | |
} | |
ngOnInit() { | |
this.socket.on("error", err => { | |
console.log(">>>>>>>>>>", err); | |
switch (err) { | |
case "AUTH_FAILED": | |
console.log("authentication failed"); | |
this.socket.disconnect(true); | |
break; | |
default: | |
break; | |
} | |
}); | |
this.socket.on("disconnect", data => { | |
console.log("---------------", data); | |
}); | |
} |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// server side | |
export function attachEvents(io) { | |
ioConn = io; | |
io.use(async (socket, next) => { | |
const token = socket.handshake.query["access-token"]; | |
const user = await validateUserToken(token).catch(err => { | |
next(new Error("AUTH_FAILED")); | |
}); | |
socket.myUser = user; | |
return next(); | |
}); | |
ioConn.on("connection", socket => { | |
if (socket.myUser && socket.myUser.get("id")) socketStore[socket.myUser.get("id")] = socket; | |
}); | |
ioConn.on("disconnect", socket => { | |
socket.disconnect(true); | |
if (socketStore[socket.myUser.get("id")]) delete socketStore[socket.myUser.get("id")]; | |
}); | |
} |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// server side | |
const io = require("socket.io")(http, { path: "/chat" }); | |
attachEvents(io); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment