websocket搭建简易的聊天室--勿喷

Posted 晚星@

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了websocket搭建简易的聊天室--勿喷相关的知识,希望对你有一定的参考价值。

因为本人做了信息的存储所以还用到的mysql,如果不做存储的话只能吧相应的代码注释即可。

node初始化 npm init 安装以下两个依赖

"mysql": "^2.18.1",
"nodejs-websocket": "^1.7.2"

建立一个app.js

var ws = require("nodejs-websocket");
console.log("开始建立连接...")


var mysql = require('mysql');
console.log('开始连接数据库.....');
var connection = mysql.createConnection(
  host: '127.0.0.1',
  user: 'root',
  password: '123456',
  database: 'socker',
  port: '3306'
);
connection.connect();
console.log('连接数据库成功!');

var [user1, user2, user1Ready, user2Ready] = [null, null, false, false];
var count1 = 0
var count2 = 0

ws.createServer(function (conn) 
  conn.on("text", function (str) 
    console.log("收到的信息为:" + str)

    var obj = 
    if (str.indexOf('mes') != -1) 
      obj = JSON.parse(str)
    

    if (str === "user1") 
      user1 = conn;
      user1Ready = true;
    
    if (str === "user2") 
      user2 = conn;
      user2Ready = true;
    


    if (user2Ready) 
      // 查历史记录
      if (count2 == 0) 
        count2++
        let sql = 'SELECT * FROM message';
        connection.query(sql, function (err, result) 
          if (err) 
            console.log('[SELECT ERROR] - ', err.message);
            return;
          

          console.log('--------------------------SELECT2222222222----------------------------');
          console.log(result);
          console.log('------------------------------------------------------------\\n\\n');
          for (let i in result) 
            let user = new String(result[i].user)
            let msg = new String(result[i].message)
            let defaultObj =  name: user, mes: msg 
            user2.sendText(JSON.stringify(defaultObj));
          
        );
       else 
        user2.sendText(str);
      
    

    if (user1Ready) 
      // 查历史记录
      if (count1 == 0) 
        count1++
        let sql = 'SELECT * FROM message';
        connection.query(sql, function (err, result) 
          if (err) 
            console.log('[SELECT ERROR] - ', err.message);
            return;
          

          console.log('--------------------------SELECT11111111111----------------------------');
          console.log(result);
          console.log('------------------------------------------------------------\\n\\n');
          for (let i in result) 
            let user = new String(result[i].user)
            let msg = new String(result[i].message)
            let defaultObj =  name: user, mes: msg 
            user1.sendText(JSON.stringify(defaultObj));
          
        );
       else 
        user1.sendText(str);
      
    



    // 数据库存谁发的信息
    if (user1Ready && user2Ready) 
      if (str.indexOf('mes') != -1) 
        mysqlMessage(obj.name, obj.mes)
      
    
  )
  conn.on("close", function (code, reason) 
    connection.end();
    console.log("关闭连接")
  );
  conn.on("error", function (code, reason) 
    connection.end();
    console.log("异常关闭")
  );
).listen(8001)


// 插入数据库数据
function mysqlMessage (name, message) 
  var addSql = 'INSERT INTO message(id,message,user) VALUES(0,?,?)';
  var addSqlParams = [message, name];
  connection.query(addSql, addSqlParams, function (err, result) 
    if (err) 
      console.log('[INSERT ERROR] - ', err.message);
      return;
    

    console.log('--------------------------INSERT----------------------------');
    console.log('INSERT ID:', result);
    console.log('-----------------------------------------------------------------\\n\\n');
  );


console.log("WebSocket建立完毕")

建立两个页面

user1.html

<!doctype html>
<html lang="en">

<head>
  <meta charset="UTF-8">
  <title>user1</title>
  <style>
    #mes 
      width: 300px;
      height: 300px;
      border: 1px solid #666;
      overflow: auto;
      margin-bottom: 10px;
      padding: 5px;
    

    li 
      text-decoration: none;
      background: #f4f4f4;
      padding: 5px;
      margin-top: 5px;
    

    .tl 
      color: red;
      text-align: left;
    

    .tr 
      color: green;
      text-align: right;
    
  </style>
</head>

<body>
  <ul id="mes"></ul>
  <div class="kuang">
    <input type="text" value="" class="int">
    <button class="send">发送</button>
  </div>
  <script>
    var mes = document.getElementById("mes");
    if (window.WebSocket) 
      var ws = new WebSocket('ws://localhost:8001');

      ws.onopen = function (e) 
        console.log("连接服务器成功");
        ws.send("user1");
      

      ws.onmessage = function (e) 
        console.log(e);
        if (e.data !== "user1" && e.data !== "user2") 
          console.log(e);
          var newData = JSON.parse(e.data);
          var node = document.createElement("LI");
          var textnode = document.createTextNode(newData.mes);
          node.appendChild(textnode);
          if (newData.name === "user2") 
            node.classList.add("tl")
            mes.appendChild(node);
           else 
            node.classList.add("tr")
            mes.appendChild(node);
          
        
        document.querySelector(".send").onclick = function (e) 
          var obj = 
            name: "user1",
            mes: document.querySelector(".int").value
          
          ws.send(JSON.stringify(obj));
          document.querySelector(".int").value = "";
        
        // 回车事件
        document.onkeydown = function (event) 
          var e = event || window.event || arguments.callee.caller.arguments[0];
          if (e && e.keyCode == 13)  // enter 键
            var obj = 
              name: "user1",
              mes: document.querySelector(".int").value
            
            ws.send(JSON.stringify(obj));
            document.querySelector(".int").value = "";
          
        

        ws.onclose = function (e) 
          console.log("服务器关闭");
        

        ws.onerror = function () 
          console.log("连接出错");
        
      
    
  </script>
</body>

</html>

user2.html

<!doctype html>
<html lang="en">

<head>
  <meta charset="UTF-8">
  <title>user2</title>
  <style>
    #mes 
      width: 300px;
      height: 300px;
      border: 1px solid #666;
      overflow: auto;
      margin-bottom: 10px;
      padding: 5px;
    

    li 
      text-decoration: none;
      background: #f4f4f4;
      padding: 5px;
      margin-top: 5px;
    

    .tl 
      color: red;
      text-align: left;
    

    .tr 
      color: green;
      text-align: right;
    
  </style>
</head>

<body>
  <ul id="mes"></ul>
  <div class="kuang">
    <input type="text" value="" class="int">
    <button class="send">发送</button>
  </div>
  <script>
    var mes = document.getElementById("mes");
    if (window.WebSocket) 
      var ws = new WebSocket('ws://10.238.91.55:8001');
      ws.onopen = function (e) 
        console.log("连接服务器成功");
        ws.send("user2");
      

      ws.onmessage = function (e) 
        if (e.data !== "user1" && e.data !== "user2") 
          console.log(e);
          var newData = JSON.parse(e.data);
          var node = document.createElement("LI");
          var textnode = document.createTextNode(newData.mes);
          node.appendChild(textnode);
          if (newData.name === "user1") 
            node.classList.add("tl")
            mes.appendChild(node);
           else 
            node.classList.add("tr")
            mes.appendChild(node);
          
        
        document.querySelector(".send").onclick = function (e) 
          var obj = 
            name: "user2",
            mes: document.querySelector(".int").value
          
          ws.send(JSON.stringify(obj));
          document.querySelector(".int").value = "";
        
        // 回车事件
        document.onkeydown = function (event) 
          var e = event || window.event || arguments.callee.caller.arguments[0];
          if (e && e.keyCode == 13)  // enter 键
            var obj = 
              name: "user2",
              mes: document.querySelector(".int").value
            
            ws.send(JSON.stringify(obj));
            document.querySelector(".int").value = "";
          
        
      

      ws.onclose = function (e) 
        console.log("服务器关闭");
      

      ws.onerror = function () 
        console.log("连接出错");
      
    
  </script>
</body>

</html>

演示截图
user1 视角

user2视角


数据库简单的设计

以上是关于websocket搭建简易的聊天室--勿喷的主要内容,如果未能解决你的问题,请参考以下文章

搭建Websocket简易聊天室

swoole用WebSocket服务器搭建一个简易的聊天室功能

swoole用WebSocket服务器搭建一个简易的聊天室功能

菜鸟|搭建WebSocket简易聊天室

《菜鸟教程》| Egret搭建WebSocket简易聊天室

使用nodeSocket.io 搭建简易聊天室