1. 程式人生 > >基於node.js打造一個簡易的聊天室

基於node.js打造一個簡易的聊天室

1.先寫服務端的程式碼
在服務端要先進行安裝node環境,然後用npm install socket.io
要安裝express框架

let http = require('http');
let fs = require('fs');
let ws = require('socket.io');
let express = require('express');
let app = express();//先進行express例項化
app.get('/',function(req,res){
	let html = fs.readFileSync('./clients.html')
;//同步讀取檔案 res.end(html); }); let server = http.createServer(app).listen(3001);//監聽3001埠 let io = ws(server);//把scoket服務掛載到http伺服器中,例項化 io.on('connection',function(socket){ console.log('有新使用者進入房間'); scoket.on('message',function(mes){ console.log(mes); io.emit('message',mes);//廣播訊息 }) })

2.客戶端這邊進行連線

<
!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Title</title> </head> <body> <h1> 聊天室的客戶端 </h1> <form action=""> <input type="text" name="" id="mes"> <input type="button" name="" id="btn" value=
"send"> </form> <script src="http://wulv5.com/js/socket.io.min.js"></script> <script> //每一次開啟客戶端,就相當於連線了聊天室 let socket = io.connect('/');//連線聊天室的io伺服器 let mes = document.getElementById('mes'); let btn = document.getElementById('btn'); let myMessage = ''; btn.onclick = function () { let value = mes.value; if(!value){ //當訊息為空時, return; } myMessage = value; socket.send(value); //把訊息傳送到服務端 mes.value = '';//清空文字框 } //當伺服器廣播訊息時,觸發message事件,訊息內容在回撥函式中 socket.on('message',function (mm) { let p = document.createElement('p'); p.innerHTML = mm; if(myMessage === mm){ p.style.cssText = 'color:red;margin-left:10%'; } document.body.appendChild(p); }) </script> </body> </html>