WebSocket 制作多人聊天室

本文介绍了一个基于Node.js的WebSocket实时聊天室应用的搭建过程。包括使用node-static处理静态资源、ws模块实现WebSocket服务端与客户端交互,以及具体的HTML、CSS和JavaScript代码实现。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

在node中需要安装的环境

npm install node-static --save-dev//布置静态资源服务器

npm install ws --save-dev//websocket 接口

文件目录结构 

 

html布局

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content='width=device-width,initail-scale=1'/>
  <meta content="telephone=no" name="format-detection"/>
  <meta content="address=no" name="format-detection"/>
  <title>网络聊天室</title>
  <link rel="stylesheet" href="../client.css"/>
</head>
<body>
  <div class="row">                             
   <label> 您的昵称:</label>
    <span class="name"></span>   
  </div>
  <div class="row">                             
    <label>聊天记录:</label>
    <div class="chat">
    </div>
  </div>
  <div class="row bottom">                             
    <input type="text" class="typed-message"/>
    <input type="button" value="发送消息" class="send-message" />
  </div>
  <script type="text/javascript" src="../jquery.min.js"></script>
  <script type="text/javascript" src="../client.js"></script>
</body>
</html>

cs样式表

.row{
    width:100%;
    display: block;
}
.row label{
    color:rgba(0,0,0,.3);
    font-size: 15px;
    font-family:'Times';
}
.row label+span{
    color:rgba(0,0,0,.6);
    font-size: 16px;
    font-family:'Times';
    margin-left:20px;
}
.chat{
    display:block;
    border:1px solid rgba(0,0,0,.2);
    border-radius:5px;
    width:100%;
    height:70vh;
}
.chat section{
    display: block;
    width:100%;  
    margin:10px 0px;
    padding:0px 20px;
    box-sizing: border-box;
}
.chat .user{
    display:block;
    color:rgba(12, 102, 42,1);
    font-size:15px;
}
.chat .message{
    display:block;
    color:rgba(255,0,0,.6);
    font-size:14px;
    margin:0px;
}
.bottom{
    position:fixed;
    display: flex;
    justify-content: space-around;
    flex-wrap: nowrap;
    bottom:0px;
    left:0px;
}
.bottom input[type='text']{
    display: inline-block;
    width:70%;
    line-height: 40px;
    border:1px solid rosybrown;
    color:rgba(0,0,0,.7);

}
.bottom input[type='button']{
    display: inline-block;
    width:30%;
    line-height: 40px;
    border:1px solid rosybrown;
    background-color: darksalmon;
    color:rgba(0,0,0,.7);
    
}

创建websocket服务器 ,处理进入聊天室的websocket.

var http = require('http');
var static = require('node-static');
var WebSocketServer = require('ws').Server;

var staticServer = new static.Server('../public');//处理静态资源的服务器
handleStaticServer=function(req,res){
     req.addListenner('end',function(){
         staticServer.serve(req,res);
     }).resume();
}
var uid = 1;
var wss = new WebSocketServer({port:'3000'});//创建3000的websocket服务器
wss.on('connection',function(ws){//监听连接的websockt
    ws.uid = uid;
     ws.send(JSON.stringify({
         uid:uid,
         type:'assign'
     }));
     wss.broadcast({
         uid:uid,
         type:'welcome'
     });
     ws.on('message',function(data){
         var data = JSON.parse(data);
         wss.broadcast({
             uid:data.uid,
             message:data.message,
             type:'message'
         });
     });
     ws.on('close',function(){
         wss.broadcast({
             uid:ws.uid,
             type:'leave'
         })
     });

  uid++;   
});
wss.broadcast = function(data){//广播到每个用户
    wss.clients.forEach(function each(client){
        client.send(JSON.stringify(data));
    });
};
app = http.createServer(function(req,res){
    handleStaticServer(req,res);
}).listen(8080,function(){
    console.log('you is running at http://localhost:8080');
});

发送每个具体用户的聊天数据到服务器

var uid;//游客id
var $inputM= $('.typed-message');
var $sendMB=$('.send-message');
var $name = $('.name');
var $chat = $('.chat');
var ws = new WebSocket('ws://localhost:3000');//连接3000端口的一个线程
ws.onmessage=function(data){
    console.log(data);
    var message = JSON.parse(data.data);
    uid =  message.uid;
    if(message.type == 'assign'){
        $name.text('client'+uid);
    }else if(message.type == 'welcome'){
        $chat.append('<section><label class="user">system:</label><p class="message">welcome to client'+message.uid+'</p></section');
    }else if(message.type == 'message'){
        $chat.append('<section><label class="user">client'+message.uid+'says:</label><p class="message">'+message.message+'</p></section');
    }else if(message.type=='close'){
        $chat.append('<section><label class="user">system:</label><p class="message">client'+message.uid+' is gone!</p></section');
    } 
}
$sendMB.click(function(){
    var message = $inputM.val();
    if(message == ''){
        return;
    }
    ws.send(JSON.stringify({
        uid:uid,
        message:message
    }));
    $inputM.val('');
});

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值