我希望搭建一个Web应用程序,使用Node.js作为后端的REST API,Angular 4作为前端。我想使用Socket.io实现实时通讯。如何在Node.js REST API中使用Socket.io?
我希望搭建一个Web应用程序,使用Node.js作为后端的REST API,Angular 4作为前端。我想使用Socket.io实现实时通讯。如何在Node.js REST API中使用Socket.io?
我在寻找讨论相关内容时,刚好实现了一个东西,想要分享并听取反馈。我认为socket.io是实现API的好方法,尤其适用于双向和实时通信。以下是起点:
在服务器端创建了这个文件 - socket-api-server:
"use strict";
const serverIo = require("socket.io");
const server = serverIo.listen(process.env.PORT || 8000);
const api_keys=JSON.parse(process.env.SOCKET_API_KEYS|| "[]");
/**
* Server Side
*
*/
function socketAPIServer(apis){
server.on("connection", (socket) => {
// this must be first - to block unauthenticated access to the APIs
socket.use((packet,next)=>{
if(socket.auth) return next();
else if(packet[0]==="authenticate" && api_keys.includes(packet[1])){
socket.auth=true;
socket.emit("authenticated")
return next();
}
else return next(new Error("unauthorized"));
})
socket.on("disconnect", () => {
delete socket.auth;
});
apis.forEach(api=>{
socket.on(api.name,api.func)
})
});
}
module.exports=socketAPIServer;
接下来我有一个API文件 - 但你也可以把它们放在单独的文件中:
const APIs=[
{ name: "api_name", func: (p1, p2,..., cb)=>{
cb(figure out what to send )
}
},
{ name: "another_api_name", func: (p1,cb)=>{
cb( calculate something from p1)
}
}
];
socketAPIServer(APIs);
const clientIo = require("socket.io-client");
// ensure ENV keys
if (!process.env.API_KEY) {
console.error("API_KEY needed. On bash use: export API_KEY=\"your-key-here\" or add it to your .bashrc file")
process.exit();
}
// ensure ENV keys
if (!process.env.API_URL) {
console.error("API_URL needed. On bash use: export API_URL=\"your-key-here\" or add it to your .bashrc file")
process.exit();
}
const ioClient = clientIo.connect(process.env.API_URL);
var authenticated=false;
var queued=[];
ioClient.on('connect',()=>{
console.info("client connected", ioClient.id);
ioClient.emit('authenticate', process.env.API_KEY);
ioClient.on("authenticated",()=>{
authenticated=true;
while(queued.length) queued.shift()();
})
});
function socketAPI(...args) {
if(args[0]==='disconnect')
return ioClient.close();
if(!authenticated) queued.push(()=>ioClient.emit(...args))
else
ioClient.emit(...args)
}
module.exports=socketAPI;
var socketAPI=require('./socketAPI');
socketAPI("api_name",p1,p2,results=>{
console.info(results);
})
用于测试的集合
export API_URL="http://localhost:8000"
export API_KEY="a long random string"
export API_KEYS="[\"a long random string\"]"
当您想要进行实时交互通信时,Web套接字非常方便。这意味着您需要全双工通信。 用法: npm i socket.io
io.on('connection', socket => {socket.emit('request', /* … */); // emit an event tothe socketio.emit('broadcast', /* … */); // emit an event to all connected socketssocket.on('reply', () => { /* … */ }); // listen to the event});