h 5チャットルームの実現

2986 ワード

一.通信サービスの作成
//              
//        
// 1. ws     
// 2.    ws   
// 3.      
//
//                          ,           socket

//  ws  
const WebSocket = require('ws')

//     
const ws = new WebSocket.Server({
    port: 8088,
    host: '10.31.158.22'
})

//   net-socket    

let member = 0;
const clients = {}

//     connection     
ws.on('connection', client => {
    client.name = ++member
    clients[client.name] = client

    //     message             
    client.on('message', msg => {
        console.log(`${client.name}  :${msg}`)
    })

    //       
    client.on('close', () => {
        console.log(`${client.name}    `)
    })
})

//                          

function boardCaster(client, msg) {
    //    send  
    for (var key in clients) {
        clients[key].send(`${client.name}  :${msg}`)
    }
}

第2歩.チャットインタフェースを示す静的サーバを構築する
//     ,                    

//  : client          ,        

//  : http://localhost:3000/yyb.html,      index.html

const express = require('express')

const path = require('path')

//  app        ,     (  )
const app = express()

const port = 8000

const host = '10.31.158.22'

//         
/* 
    :            ,  express         
         /client/index.html      
    :         
  //path.join               ,    2-h5
*/
app.use(express.static(path.join(__dirname, 'client')))

app.listen(port, host, () => {
    console.log(`      :http://${ host }:${ port }`)
})

第三歩.チャットルームの構造を書く




    
    
    
    WebSocket



    


var submit = document.querySelector('#submit') var msg = document.querySelector('#msg') submit.onclick = function() { ws.send(msg.value) // msg.value = '' } document.onkeydown = function(e) { if (e.keyCode === 13) { ws.send(msg.value) msg.value = '' } }

第四步.客户端连接通信服务器端

//  html    ,                 

const url = 'ws://10.31.158.22:8088'


const ws = new WebSocket(url)

ws.onopen = () => {
    //    
    ws.send('       o    ')
}

ws.onmessage = msg => {
    var content = document.querySelector('#content')
    console.log(msg)

    content.innerHTML += msg.data + '
' }