h5チャットルーム



H5 Chat Rooms



A.通信サーバーを作成します

// here is to establish a communication with the master server // master communication // 1. ws module to create // 2. Install ws module // 3. Create a server // // two programs implemented on the network to exchange data via a bidirectional communication connection, this connection is called a socket end // imports ws module const WebSocket = require('ws') // Create server const ws = new WebSocket.Server({ port: 8088, host: '10.31.158.22' }) // net-socket and following essentially the same let member = 0 const clients = {} // server connected via connection client ws.on('connection', client => { client.name = ++member clients[client.name] = client // server to accept the client sent a message by message events client.on('message', msg => { console.log ( `$ {client.name}, saying: $ {msg}`) }) // client offline behavior client.on('close', () => { console.log ( `$ {client.name}` number has been offline) }) }) // this function is used to package a client to the server at the information presentation function boardCaster(client, msg) { // send method here for (var key in clients) { clients [key] .send ( `$ {client.name}, saying: $ {msg}`) } }

チャットショー静的サーバーインターフェイスの2番目のステップの確立



// This is the second step, the establishment of a representative of a static server chat room page // mistake: client file under the name of the custom, you must remember to add the phrase // For example: http: // localhost: 3000 / yyb.html, do not write the default is index.html const express = require('express') const path = require('path') // Create app to bind middleware, middleware call (function) const app = express() const port = 8000 const host = '10.31.158.22' // specify a static resource directory /* Question: If you do not specify a static resource directory, then start the server considers express /client/index.html is a route Solution: specify a static resource directory //path.join this method causes the disk to point to the current root directory, that is where the 2-h5 */ app.use(express.static(path.join(__dirname, 'client'))) app.listen(port, host, () => { console.log ( `server runs: http: // $ {host}: $ {port}`) })

3番目のステップの書き込み構造のチャットルーム

WebSocket

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

ステップ4.クライアントサーバー通信接続



// create html structure after the fourth step is used to connect a client-server communications const url = 'ws://10.31.158.22:8088' const ws = new WebSocket(url) ws.onopen = () => { // initial connection ws.send ( 'Welcome to the studio's cold Mo o') } ws.onmessage = msg => { var content = document.querySelector('#content') console.log(msg) content.innerHTML += msg.data + '
' }