vue+websocket 온라인 채팅방

2284 단어

프런트 엔드


1. html 부분

채팅방

:{{nickName}}

{{item.nickName}} : {{item.content}}


2.js 섹션


    
        new Vue({
            el: ".container",
            mounted: function () {
                this.nickName = prompt("input your name")
                this.ws = new WebSocket("ws://localhost:3000")
                this.ws.onopen = function () {
                    console.log(" ")
                }
                var _this = this
                this.ws.onmessage = function (ev) {
                    var item = JSON.parse(ev.data)
                    _this.chatList.push(item)
                }
            },
            data: {
                ws: null,
                nickName: "",
                chatList: [],
                content: ""
            },
            methods: {
                send() {
                    var data = {
                        nickName: this.nickName,
                        content: this.content
                    }
                    // 
                    this.ws.send(JSON.stringify(data))
                }
            }
        })
    

백엔드

// ws 
var webSocket = require('ws')

var wss = new webSocket.Server({port:3000})
// 
wss.on("connection",function(ws){
    console.log(" ") 
    // 
    ws.on("message",function(data){
        wss.clients.forEach(function(client){
            // 
            client.send(data)
        })
    })  
})

console.log("websocket server is running")

좋은 웹페이지 즐겨찾기