Notice
Recent Posts
Recent Comments
Link
«   2025/06   »
1 2 3 4 5 6 7
8 9 10 11 12 13 14
15 16 17 18 19 20 21
22 23 24 25 26 27 28
29 30
Archives
Today
Total
관리 메뉴

JAVA Developer Training

26. socket.io를 이용한 실시간 채팅 기초 틀 본문

트레이닝

26. socket.io를 이용한 실시간 채팅 기초 틀

Romenest 2021. 9. 8. 12:35

환경설정, 기타 설치 카테고리의 socket.io 관련 글을 보고 와야 합니다.

 

node.js 에서

App.js 파일

var app = express();
// express 는 app변수를넣어 -> http만들고 -> socket.io 연결
var http = require('http').createServer(app);
app.io = require('socket.io')(http,{cors : {origins: '*:*'}}); //접속 조건
															//현재는 *:* 로 조건이 없는상태나 마찬가지

//클라이언트(vue, react, android 등)이 접속 했을 때
app.io.on('connection',function(socket){
  //접속한 소켓 정보 확인
  console.log(`connection ${socket}`);

  //클라이언트에서 데이터(문자,파일) 가 전송되었을떄 key=publish
  socket.on('publish',function(data){

    //전송된 데이터 출력
    console.log(data);

    //전체 클라이언트로 데이터를 전송
    app.io.emit('subscribe', {
      userid     : data.data.userid,
      username   : data.data.username,
      userage    : data.data.userage,
    });

  });

});

 

Vue에서

main.js 파일

import { createApp } from 'vue'
import App from './App.vue'



// socket.io
// npm install socket.io-client --save
//모듈 가져오기
import io from 'socket.io-client'

// 클라이언트 소켓 생성
const socket = io ("/",
{transports : ['websocket']});

const app = createApp(App);

//여러 컴포넌트에서 socket을 사용하기 위해서 설정
app.config.globalProperties.$socket = socket;

app.mount('#app');

vue에서 $socket을 입력시 불러오기 가능

 

vue.config.js 파일

module.exports = {
    devServer: {
        proxy: {
            '/': {
                target: 'http://127.0.0.1:3000',
                changeOrigin: true,
                logLevel: 'debug',
            },
            '/member': {
                target: 'http://127.0.0.1:3000',
                changeOrigin: true,
                logLevel: 'debug',
            }
        },
    }
};

소켓에서 설정한 '/' 주소 위치 설정

 

 

 

채팅 화면 구성

<template>
    <div>
        메세지 입력 <input type="text" v-model="msg" @keyup.enter="sendMassage" /> <br/>
        받은 메세지 출력 
        <table>
            <tr v-for="msg in list" v-bind:key="msg">
                <td>{{msg.userid}}</td>
                <td>{{msg.username}}</td>
                <td>{{msg.userage}}</td>
            </tr>
        </table>
    </div>
</template>

<script>
import {getCurrentInstance} from '@vue/runtime-core'
    export default {
        methods : {
            sendMassage() {
                this.$socket.emit('publish', //key는 publish 설정안하면 소켓사용불가
                {
                    data : {userid : this.msg, username : 'aaa' , userage : 343}
                    //id = 실제 적을 메세지의 내용
                    //name = 임의지정한 글쓴이 ( 이를 변경,수정하면 개인별 아이디로 지정 채팅자의 닉네임으로 설정가능)
                    //age = regdate와 같은것으로 설정하면 작성 시간으로 설정가능
                });
            }
        },
        created() { //실행시,인스턴스 작동시 자동호출
            const app = getCurrentInstance();
            this.$socket = app.appContext.config.globalProperties.$socket;
            console.log(this.$socket);
        },
        mounted() { //대체된 인스턴스 작동시 호출, 즉 기능사용시
        //변경 감지시 가 아니다. 변경감지시 알아서 되는것은 watch기능이 있다
            this.$socket.on('subscribe',(recv) => { // key는 subscribe
                console.log(recv); 			//recv로 받은 메세지를 list에 넣어준다
                this.list.push(recv);
            })
        },
        data(){
            return{
                msg : '',
                list : [],
                recv : [],
                $socket : '',
            }
        }
    }
</script>

<style scoped>

</style>

 

결과화면

 

채팅 입력전 각 cmd창

좌측 nodejs 우측 vue 

 

 

입력전
1페이지에서의 입력

 

2페이지 에서 확인
3페이지 에서도 확인 이후 메세지2 입력
페이지 3에서 채팅 송신

동일하게 확인