본문 바로가기

코딩(coding)일지/javascript

[socket + node + angular]

먼저 진짜 쪽집게 socket 

먼저 간단한 흐름을 머리속에 들고 가봅시다.

서버나 클라이언트 생각 말고 양쪽이 이건 같습니다. 

 

어렵게 설명한거 말고 이것만 기억하세요

=> on 받을 준비!!!

=> emit 데이터 준다!!!

 

<!---- -- -- -- -- -- -- -- -- -- -- -- -- --  서버 쪽 -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- >

 

1) npm install socket.io

현 기점 @4.4.1 

 

2) node 에 코드 작성

const express = require('express');
const http = require('http');
const app = express();
const server = http.createServer(app);
const io = require('socket.io')(server);
global.io = io // io를 글로벌로해서 어떠한 처리를 통해 특정인에게 보낼 수 있게 만들었습니다.

 io.on('connection',function(socket){
 
        // 특정유저의 id와 소켓id를 매치 시켜서 넣었습니다.
        global.socketUsers = [];
        global.socket = socket;
        
        // 연결 
        socket.on('entry',(userId)=>{
            const idx = socketUsers.findIndex(el => el.id == userId);
            
            if(idx == -1) {
            socketUsers.push(
                {
                id : userId,
                socket_id : socket.id
                }
            )
            } else {
            socketUsers[idx].socket_id = socket.id
            }
        })
        });

문제점 : 현재는 유저 아이디없이 얻게 되는 소켓 id에 disconnect가 없는 상태 입니다.

=> 추후 해결법을 올리겠습니다.

 

3) 처리 후 발생시키기

router.post('/test123', async(req,res)=>{
    try {
        /*
           원하는 유저 아이디를 검색해서 보낼 수 있습니다.
        */

        // ex : 아까 넣어둔 특정 아이디에게 snackbar 내용 보내기
        // io.to(특정소켓아이디).emit('name', data)
        io.to(socketUsers[0].socket_id).emit('snackbar',['hihi','hello'])
        
        // 전체에게 보내기
      	io.socket.emit('snackbar',['hihi','hello'])
        
    } catch (error) {
    
    }
})

 

<!-- -- -- -- -- -- -- -- -- -- -- -- -- --  클라이언트 쪽 -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- >

 

1) npm i socket.io-client  ,  npm i socket.io

* cdn을 사용하거나 해도 되는데 , 본 작업이 angular이기 때문 npm 사용하였습니다.

 

2) 소켓 통신은 서비스로 빼주었습니다.

import { Injectable } from '@angular/core';
import { Subject , Observable} from 'rxjs';
import { io } from "socket.io-client";
import { environment } from 'src/environments/environment';

@Injectable({
  providedIn: 'root'
})
export class SocketService {

  constructor() { }
  
  private socket:any = io(environment.serverUrl);

  // 소켓으로 데이터 보낼때 대비
  sendData(msg) {
    this.socket.emit('access', msg);
  }

  // 소켓으로 데이터 받을때 대비
  getData(Eventname : String) {
    let observable = new Observable(observer => {
      this.socket.on(Eventname, (data:any) => {
        observer.next(data);    
      });
    })     
    return observable;
  }
  
  // 연결은 자동으로 되지만 , 특정유저 id를 보내 매치시켰습니다.(채팅 아닌것의 한계)
  connection(type,msg) {
    this.socket.emit(type, msg);
  }
}

 

3) 사용할 컴포넌트 

	// 받고 싶은 데이터 대기 상태
    
	this.socketService.getData('snackbar').subscribe(res =>{
      console.log(res);
    })
    
    // 보내고 싶은 데이터 
    this.socketService.connection('entry',1);

'코딩(coding)일지 > javascript' 카테고리의 다른 글

[javascript] 전체 화면 만들기  (0) 2022.03.25
[vue] vuex 와 vue.observable  (0) 2021.12.28