Hi,my friend and I are making our student project.And so far we create our 'back end' but in front (angular) somehow we are not able to get new socket.id when user change room.I will share your code with me hope someone will be able to help.

This is our ANGULAR code

import { Component, OnInit } from '@angular/core';
import { ActivatedRoute, Params, Router } from '@angular/router';
import { Observable } from 'rxjs';
import { io } from 'socket.io-client';
import { environment } from '../../../environments/environment';
import { LoadingService } from '../../shared/services/loading.service'
import { ChatService } from './chat.service';
@Component({
  selector: 'app-chat',
  templateUrl: './chat.component.html'
})
export class ChatComponent implements OnInit {
  private socket;
  // private socketClosed;
  chatOptions: { name: string, code: string }[];
  selectedOption: { name: string, code: string };
  choosedArray: any[] = [];
  selectedElement: any;
  historyMessages: any = [];
  userInfo: any;
  // newArray: any[] = [];
  newMessage: any;
  showChatSection: boolean = false;
  constructor(
    private router: Router,
    private activatedRoute: ActivatedRoute,
    private loadingService: LoadingService,
    private chatService: ChatService
  ) {
    this.chatOptions = [
      { name: 'Otvoreni', code: 'active' },
      { name: 'Zatvoreni', code: 'closed' },
    ];
    this.selectedOption = this.chatOptions[0];
  }
  ngOnInit(): void {
    this.socket = io(environment.socket_endpoint);
    this.selectedOption.code === 'active' ? this.onSelectActiveRooms() :
      this.onSelectClosedRoom();
    // this.chatService.newMessageReceived().subscribe(responseMsg => {
    //   console.log(responseMsg);
    //   this.historyMessages.push(responseMsg);
    //   this.newMessage = '';
    // });
    this.newMessageReceived().subscribe(responseMsg => {
      console.log(responseMsg);
      this.historyMessages.push(responseMsg);
      this.newMessage = '';
    })
  }
  onSelectRoom() {
    this.selectedOption.code === 'active' ? this.onSelectActiveRooms() :
      this.onSelectClosedRoom();
    // Da se zatvori trenutna soba kada se prelazi na novi chat
    this.closeChat();
  }
  closeChat() {
    this.selectedElement = false;
    // console.log(this.selectedElement);
  }
  onSelectActiveRooms() {
    this.choosedArray = [];
    this.socket = io(environment.socket_endpoint);
    this.socket.on('listOfAllRoom', (roomsOption) => {
      console.log(roomsOption);
      this.choosedArray = roomsOption;
    })
  }
  onSelectClosedRoom() {
    this.choosedArray = [];
    // console.log(this.selectedOption)
    this.socket = io(`${environment.socket_endpoint}/closed`);
    this.socket.on('closedRoom', msg => {
      console.log(msg);
      this.choosedArray = msg;
    })
  }
  joinRoom(element: any) {
    this.showChatSection = false;
    this.selectedElement = element;
    const username = "admin";
    const room = this.selectedElement.room;
    const queryParams: Params = { username: username, room: room };
    this.router.navigate([], { relativeTo: this.activatedRoute, queryParams: queryParams, });
    this.socket.emit('joinRoom', { username, room });
    setTimeout(() => {
      this.scrollToFunc();
      this.showChatSection = true;
    }, 400);
  }
  onSelectedChat(element: any) {
    // this.showChatSection = false;
    // const username = "admin"
    // this.selectedElement = element;
    // const queryParams: Params = { username: username, room: this.selectedElement.room };
    // this.router.navigate([], { relativeTo: this.activatedRoute, queryParams: queryParams, });
    // const room = this.selectedElement.room;
    // this.chatService.joinRoom({ username: username, room: room })
    // this.socket.emit('join', { username, room });
    // this.socket.once('historyMessageAdmin', (chatHistory) => {
    //   console.log(chatHistory);
    //   this.historyMessages = chatHistory.chat;
    //   this.userInfo = chatHistory.userInfo[0];
    //   // this.socket.removeAllListeners()
    // });
    // setTimeout(() => {
    //   this.scrollToFunc();
    //   this.showChatSection = true;
    // }, 400);
  }
  scrollToFunc(smooth?: boolean) {
    // console.log(smooth);
    const scrollContainer = document.getElementById('messages');
    scrollContainer.scrollTo({
      top: scrollContainer.scrollHeight,
      left: 0,
      behavior: smooth === true ? 'smooth' : 'auto'
    });
  }
  sendMessageToClients() {
    console.log(this.newMessage);
    const user = 'admin';
    const room = this.selectedElement.room;
    const message = this.newMessage;
    this.socket.emit('newMessageToServer', { user, room, message });
    // this.chatService.sendMessage({ user, room, message });
    const smooth = true;
    setTimeout(() => {
      this.scrollToFunc(smooth);
    }, 400);
  }
  newMessageReceived() {
    let observable = new Observable<any>(observer => {
      this.socket.on('messageToClients', (responseMsg) => {
        // console.log(responseMsg);
        observer.next(responseMsg);
      });
      return () => { this.socket.disconnect(); }
    });
    return observable;
  }
}


And this is our Node code 


const moment = require('moment');
const geoip = require('geoip-lite');
let parser = require('ua-parser-js');
let { io } = require('./../app');
const chat = () => {
    io.on('connection', async (socket) => {
        socket.on('join', async (data) => {
            console.log(data.room)
            const findAllRoom = await Chat.find().where('isActive').equals(true).select('-_id room').sort('-last_message')
            io.emit('listOfAllRoom', findAllRoom)
            let username = data.username;
            let room = data.room;
            socket.join(room);
            console.log(`Connected in room ${room}`)
            console.log(socket.rooms);
            const c = await Chat.findOne({ room: room });
            if(c.room === ''){
                //console.log('its empty')
            }
            if (!c) {
                const createRoom = await Chat.create({
                    username: data.username,
                    room: data.room
                })
                const insternalInfo = parser(socket.request.headers['user-agent']);

                const browser = insternalInfo.browser.name;
                const os = insternalInfo.os.name;
                const ip = socket.handshake.address;

                const ipAddress = "46.33.205.136";
                const location = geoip.lookup(ipAddress);
                const pushInfo = await Chat.findOneAndUpdate({ room: createRoom.room }, {
                    $push: {
                        userInfo: { name: username, location: location.city, browser: browser, os: os, ip_address: ipAddress }
                    }
                })
                const findAllRoom = await Chat.findById(createRoom.id)
                io.emit('listOfAllRoom', findAllRoom.room)
            } else {
                const chat = c.chat;
                if (username == 'admin') {
                    const roomInfo = await Chat.findOne({ room: room }).select('chat userInfo')

                    io.to(room).emit('historyMessageAdmin', roomInfo);
                } else if (username == username) {
                    io.to(room).emit('historyMessage', chat);
                }
            }
            socket.on('newMessageToServer', async (message) => {
                //console.log(message)
                console.log(socket.rooms)
                const timeForMongo = moment().format();
                const time = moment(Date.now()).locale('me').format('LT');
                const sendmessage = await Chat.findOneAndUpdate({ room: room }, {
                    $push: {
                        chat: { message: message, name: username, time: moment(Date.now()).locale('me').format('LT') }
                    }
                })
                const sendMessageTime = await Chat.findOneAndUpdate({room:room},{
                    last_message:Date.parse(timeForMongo)
                })
                console.log(sendMessageTime);
                const findAllRoom = await Chat.find().select('-_id room').where('isActive').equals(true).sort('-last_message')
                io.emit('listOfAllRoom',findAllRoom);
                console.log(findAllRoom)
                io.to(room).emit('messageToClients', ({ message, username, time }));
            })
            //io.to(room).broadcast.emit('newClient', 'Clinet logged in')
        });
    });
}
    io.of('/closed').on('connection', async (socket) => {
        socket.on('join', async(data) =>{
            console.log(data)
            const findBlockedRoom = await Chat.find().where('isActive').equals(false).select('-_id room');
            socket.emit('closedRoom', findBlockedRoom);
            console.log(findBlockedRoom)
        });
});
module.exports = chat;

This question needs refinement. You wrote about your issue but then supplied hundreds of lines of code without an overview or where you think the system failed.

My thought is that the change in room should be similar to the initial join but with the new connection. Tell more where you think this failed in your code (by line number.)

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts learning and sharing knowledge.