# go into project foldercd socket-cluster-app/
# generate socket modulenest g module socket
# generate socket servicenest g service socket
# generate socket gatewaynest g gateway socket/socket
import{OnGatewayConnection,OnGatewayDisconnect,WebSocketGateway,}from"@nestjs/websockets";@WebSocketGateway()exportclassSocketGatewayimplementsOnGatewayConnection,OnGatewayDisconnect{publicconnectedSockets:{[key:string]:any[]}={};asynchandleConnection(client:any,req:Request){try{consttoken=req.headers["cookie"].split(";").map((p)=>p.trim()).find((p)=>p.split("=")[0]==="token").split("=")[1];// for this example, we simply set userId by tokenclient.userId=token;if(!this.connectedSockets[client.userId])this.connectedSockets[client.userId]=[];this.connectedSockets[client.userId].push(client);}catch(error){client.close(4403,"set JWT cookie to authenticate");}}handleDisconnect(client:any){this.connectedSockets[client.userId]=this.connectedSockets[client.userId].filter((p)=>p.id!==client.id);}}
constws=require("ws");constport=3001;constsocket=newws(`ws://localhost:${port}`,{headers:{Cookie:"token=user1"},});socket.on("message",(data)=>{console.log(`Received message`,data);});socket.on("open",(data)=>{console.log(`Connected to port ${port}`);});socket.on("close",(data)=>{console.log(`Disconnected from port ${port}`);});
constructor(private readonly socketGateway: SocketGateway){ this.serviceId ='SOCKET_CHANNEL_' + Math.random() .toString(26) .slice(2); setInterval(()=> { this.sendMessage('user1',
new Date().toLocaleTimeString() +
`| from server on port ${process.env['PORT']}`,
false,
);}, 3000);}
import{Injectable,OnModuleDestroy,OnModuleInit}from"@nestjs/common";import{createClient,RedisClient}from"redis";import{SocketGateway}from"./socket.gateway";@Injectable()exportclassSocketServiceimplementsOnModuleInit,OnModuleDestroy{publicredisClient:RedisClient;publicpublisherClient:RedisClient;privatesubscriberClient:RedisClient;privatediscoveryInterval;privateserviceId:string;constructor(privatereadonlysocketGateway:SocketGateway){this.serviceId="SOCKET_CHANNEL_"+Math.random().toString(26).slice(2);setInterval(()=>{this.sendMessage("user1",newDate().toLocaleTimeString()+` | from server on port ${process.env["PORT"]}`,false);},3000);}asynconModuleInit(){this.redisClient=awaitthis.newRedisClient();this.subscriberClient=awaitthis.newRedisClient();this.publisherClient=awaitthis.newRedisClient();this.subscriberClient.subscribe(this.serviceId);this.subscriberClient.on("message",(channel,message)=>{const{userId,payload}=JSON.parse(message);this.sendMessage(userId,payload,true);});awaitthis.channelDiscovery();}privateasyncnewRedisClient(){returncreateClient({host:"localhost",port:6379,});}asynconModuleDestroy(){this.discoveryInterval&&clearTimeout(this.discoveryInterval);}privateasyncchannelDiscovery(){this.redisClient.setex(this.serviceId,3,Date.now().toString());this.discoveryInterval=setTimeout(()=>{this.channelDiscovery();},2000);}asyncsendMessage(userId:string,payload:string,fromRedisChannel:boolean){this.socketGateway.connectedSockets[userId]?.forEach((socket)=>socket.send(payload));if(!fromRedisChannel){this.redisClient.keys("SOCKET_CHANNEL_*",(err,ids)=>{ids.filter((p)=>p!=this.serviceId).forEach((id)=>{this.publisherClient.publish(id,JSON.stringify({payload,userId,}));});});}}}
import{OnGatewayConnection,OnGatewayDisconnect,WebSocketGateway,}from"@nestjs/websockets";@WebSocketGateway()exportclassSocketGatewayimplementsOnGatewayConnection,OnGatewayDisconnect{publicconnectedSockets:{[key:string]:any[]}={};asynchandleConnection(client:any,req:Request){try{consttoken=req.headers["cookie"].split(";").map((p)=>p.trim()).find((p)=>p.split("=")[0]==="token").split("=")[1];// for this example, we simply set userId by tokenclient.userId=token;if(!this.connectedSockets[client.userId])this.connectedSockets[client.userId]=[];this.connectedSockets[client.userId].push(client);}catch(error){client.close(4403,"set JWT cookie to authenticate");}}handleDisconnect(client:any){this.connectedSockets[client.userId]=this.connectedSockets[client.userId].filter((p)=>p.id!==client.id);}}