socket聊天室实现啦

最近新get了一招,先上图:

看到这是不是很熟悉呢,有没有一种想拿鼠标拖一拖的错觉呢。没错它就是模仿了qq群聊的样式,不过功能暂时不多只能发文字。这个在线聊天室使用了web-socket协议的功能并以node.js为后台进行编写,具体实现的机制是:

    每个用户向进入界面后将与服务器连接,连接成功后用户向服务器发送的消息将被广播到所有正在连接该服务器的用户(即把该消息发送到连接到服务器的所有用户,因此实现了群聊的功能)

①用户将通过 var socket = io.connect("/") 发起与服务器的连接,服务器通过io.on("connection",function(socket){}响应。

②前端通过socket.send()进行发送,后台通过socket.on('message',function(msg))  接收,io.mit('message',msg)广播。

 

后台代码:

const http = require("http");
const fs = require('fs');
const ws = require("socket.io");

let friends = [];
const server = http.createServer(function(req,res){
  // 读取文件,发送到前端
  const html = fs.readFileSync('./www/index.html');
  res.write(html);
});
// 基于当前web服务开启socket实例
const io=ws(server);
// 检测连接事件
io.on("connection",function(socket){
  console.log('连接');
  // 接收客户端发送的消息,并广播出去
  socket.on("message",function(mes){
    console.log(mes);
    // 向所有的客户端广播消息
    if(mes.msg==undefined){
      if(mes.out) {
        // io.emit("message",mes);
        friends.splice(friends.indexOf(mes.out),1);
        io.emit("message",{"friends":friends,"out":mes.out});
      }else {
        friends.push(mes);
        console.log("friends"+friends);
        io.emit("message",{"friends":friends,"add":mes});
      }
    }else {
        // console.log(mes);
        io.emit("message",mes);
    }
  });
})
server.listen(8080);

 

node刚学,可能写的很丑,忘留下宝贵建议。

前端(html)

<body>
    <p id="agin">刷新重来</p>
    <div id="container">
      <div id="head">
        进来的都是真爱,发给好友试试吧
      </div>
      <div id="record-box">
        <div id="addInfo">
            qpq加入聊天室
        </div>
      </div>
      <div id="friends-box">
        <p>群成员 <span>10</span></p>
        <ul id="friend-list">
          <!-- <li><em></em><span>sjkcnb</span></li> -->
        </ul>
      </div>
      <div id="send-box">
        <div class="function">
          表情功能,尽情期待……
          <div class="look">
            <!-- <img src="img/Smile.png" alt="smile" width="100%"> -->
 
  • 4
    点赞
  • 21
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值