nodejs 實現即時通訊 聊天室demo
需要安裝 nodejs-Websocket
服務端
var ws = require("nodejs-websocket"); console.log("開始建立連線...")
var game1 = null,game2 = null , game1Ready = false , game2Ready = false; var server = ws.createServer(function(conn){ conn.on("text", function (str) { if(str==="key1"){ game1 = conn; game1Ready = true; conn.sendText("success"); } if(str==="key2"){ game2 = conn; game2Ready = true; }
if(game1Ready&&game2Ready){ game2.sendText(str); game1.sendText(str); }
conn.sendText(str)//傳送給客戶端訊息 }) conn.on("close", function (code, reason) { console.log("關閉連線") }); conn.on("error", function (code, reason) { console.log("異常關閉") }); }).listen(8001) console.log("WebSocket建立完畢")
客戶端
<input id='msg'>第一次輸入對方的key <h1 onclick='send()'>send</h1>
<script>
var wsServer = 'ws://127.0.0.1:8001'; var websocket = new WebSocket(wsServer);
websocket.onopen = function (evt) {//連結成功事件 console.log("Connected to WebSocket server.",'evt:'+evt); };
websocket.onclose = function (evt) {//關閉連結事件 console.log("Disconnected",'evt:'+evt); };
websocket.onmessage = function (evt) {//接收訊息事件 服務端 sendText事件 觸發此事件 console.log('Retrieved data from server: ' + evt.data); };
websocket.onerror = function (evt, e) {//發生錯誤後的事件 console.log('Error occured: ' + evt.data); }; console.log(websocket); function send(){ let v = document.getElementById('msg').value;
websocket.send(v);//觸發 服務端 message 事件
}
</script>
很簡單的demo