nodejs+websocket聊天工具

來源:互聯網
上載者:User

標籤:啟動   break   set   lock   cli   let   show   pip   osi   

該聊天工具,使用nodejs起服務,websocket前端頁面,聊天工具,,可以有任意多的人數參與聊天,裡面的使用者ID為類比ID。

先

 

 檔案夾結構,

1、安裝ws模組,npm install ws

 

2、web.js檔案,是Nodejs後端代碼

var WebSocketServer = require(‘ws‘).Server,wss = new WebSocketServer({ port: 8181 });//var client1 = null,client2=null,client1Ready = false, client2Ready = false;var config = {};var userList = {};wss.on(‘connection‘, function (ws) {    console.log(‘client connected‘);    ws.on(‘message‘, function (message) {      var data = JSON.parse(message);      console.log(data);      if(data.type == ‘register‘){      console.log("register");      config[data.meID]  =  {ID:data.meID,myNike:data.sendNike,pipe:ws,Ready:true};      userList[data.meID] = {ID: data.meID,myNike: data.sendNike};      refreshList();            }else if(data.type == ‘sendMessage‘){      console.log("send");      sendMessage(data);      }else{      ws.send(JSON.stringify({"error":true}));      }                   });        ws.on("close",function(code, reason){        for(var i in config){    if(config[i].pipe === ws){    config[i].Ready = false;    config[i].pipe = null;    delete config[i];    delete userList[i];    refreshList();    break;    }    }    console.log("關閉連結");    });         });//更新聊天列表function refreshList(){for(var i in config){config[i].pipe.send(JSON.stringify({‘type‘:‘refreshList‘,‘list‘:userList}));}}//更新聊天function sendMessage(data){if(config[data.receiveID]){//對方線上data.sendNike = userList[data.meID].myNike;config[data.meID].pipe.send(JSON.stringify(data));config[data.receiveID].pipe.send(JSON.stringify(data));}else{//對方不線上config[data.meID].pipe.send(JSON.stringify({"error":true}));}}//npm install ws

  

2、添加用戶端client.html

<!DOCTYPE html><html><head><meta charset="UTF-8"><title>client1</title><style type="text/css">*{padding: 0;margin: 0;font-family: "微軟雅黑";}#chat{width: 600px;height: 400px;margin: 50px auto;border: 4px solid yellowgreen;}p{font-size: 16px;color: #9ACD32;padding: 0 20px;}#chat p.send{text-align: right;color: deeppink;}#chat p.receive{text-align:left ;}.btn{text-align: center;}.showState{text-align: center;}.showInfo{text-align: center;}div.firend{width: 200px;}div.firend p{height: 30px;text-align: center;line-height: 30px;background: deeppink;color: #fff;}ul.list{width: 200px;}ul.list li{height: 30px;line-height: 30px;background: #9ACD32;color: #fff;text-align: center;border: 1px solid #000;cursor: pointer;position: relative;}ul.list li span{position: absolute;width: 20px;height: 20px;text-align: center;line-height: 20px;font-size: 14px;border-radius: 10px;background: red;color: #fff;right: -10px;top: 5px;display: none;}</style></head><body><div class="showState">正在連結..</div><div class="showInfo"></div><div id="chat"></div><div class="btn"><input type="text" name="message" id="message" value="" /><button onclick="sendMessage()">發送</button></div><div class="firend"><p>線上好友名單</p><ul class="list"></ul></div></body><script type="text/javascript" src="jquery.js"></script><script type="text/javascript">var sendConfig = {"type":"send","meID":getName(),"sendNike":"client1","receiveNike":"","receiveID":‘‘};var register = {"type":"register","sendNike":sendConfig.sendNike,"meID":sendConfig.meID}var messageList = {};//隨機擷取名稱function getName() {var timer = new Date();var arr = JSON.stringify(timer).replace(/:|-|"/g, ‘‘).split(‘.‘);var str = arr.join(‘‘);console.log(str);return str;}var mes = document.getElementById("message");var box = $("#chat");var chatWith = $(".showInfo");var showState = $(".showState");var personList = $(".list");var ws = new WebSocket("ws://localhost:8181");ws.onopen = function (e) {ws.send(JSON.stringify(register));showState.html("連結成功!");// chatWith.html("你正在和:"+ sendConfig.receiveNike + "聊天");}//接收聊天資訊ws.onmessage=function (e) {var data = JSON.parse(e.data);if(data.type == ‘refreshList‘){refreshList(data.list);}else if(data.type == ‘sendMessage‘){messageStore(JSON.parse(e.data));}};//記錄訊息通訊function  messageStore(data) {var recodeId1 = data.receiveID + "&" + data.meID;var recodeId2 = data.meID  + "&" + data.receiveID;if(messageList[recodeId1]){messageList[recodeId1].push(data);}else if(messageList[recodeId2]){messageList[recodeId2].push(data);}else{messageList[recodeId1] = [];messageList[recodeId1].push(data);}//create(data);alertmessage(data);}//提示訊息來了function alertmessage(data) {var liList = $(‘ul.list‘).find(‘li‘);for(var i = 0; i < liList.length ; i++ ){if(liList.eq(i).attr(‘userId‘) == data.meID){ //找到對應的訊息接收者if(data.meID != sendConfig.meID){   //排除自己if(data.meID != sendConfig.receiveID){  //排除正在聊天的人var $span = liList.eq(i).find(‘span‘);$span.css(‘display‘,‘block‘);$span.html($span.html()*1+1);}else{create(data);}}else{create(data);}break;}}}//更新好友名單function refreshList(data){console.log(data);personList.html(‘‘);for(var  i in data){if(data[i].ID == sendConfig.meID){personList.append(‘<li userId =‘ + data[i].ID  + ‘ > <strong>自己 </strong> <span>0</span> </li>‘)}else{personList.append(‘<li userId =‘ + data[i].ID  + ‘ ><strong>‘+ data[i].myNike  +‘</strong><span>0</span></li>‘)}}}//選擇聊天對象$(".list").on("click","li",function(){box.html(‘‘);chatWith.html("你正在和:"+ $(this).find(‘strong‘).html() + "聊天");sendConfig.receiveID = $(this).attr(‘userId‘);//取出聊天記錄var recodeId1 = sendConfig.receiveID + "&" + sendConfig.meID;var recodeId2 = sendConfig.meID  + "&" + sendConfig.receiveID;if(messageList[recodeId1]){getMessageRecod( messageList[recodeId1]);}else if(messageList[recodeId2]){getMessageRecod( messageList[recodeId2]);}//隱藏訊息提示$(this).find(‘span‘).css(‘display‘,‘none‘).html(‘0‘);});//取出聊天記錄,並且渲染function  getMessageRecod(data) {if(data){for(var i = 0; i < data.length ; i++){create(data[i]);}}}//建立標籤function create(data){if(data.error){alert("發送失敗,對方不線上!");}else {if (data.meID == sendConfig.meID) {box.append("<p class=‘send‘>" + sendConfig.sendNike + ":" + data.message + "</p>");} else {box.append("<p class=‘receive‘>" + data.sendNike + ":" + data.message + "</p>");}}}//發送聊天資訊function sendMessage() {if(sendConfig.receiveID == ‘‘){alert(‘沒有選擇發送訊息對象!‘);}else{var mesage = {"type":"sendMessage","meID":sendConfig.meID,"receiveID":sendConfig.receiveID,"message":mes.value,};var str = JSON.stringify(mesage);ws.send(str);}}</script></html>

  3、添加用戶端,client2.html,client3.html,,,只需要修改client1.html中,config的sendNick,

 

4、注意添加jquery檔案

 

5、nodejs啟動web.js檔案,開啟所有.html檔案,進行聊天。

 

nodejs+websocket聊天工具

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.