使用nodejs搭建聊天室

本文指导如何利用Node.js搭建一个服务器,并通过下载socket.io插件,创建静态文件夹存放index.html,最后启动服务器,用户可以通过浏览器访问http://localhost:10010/index.html体验实时聊天功能。

搭建一个服务器


//引入fs
var fs = require('fs')
//引入http 
var http = require('http')
var date = new Date()
/**
 * @FormDate 格式化时间
 * @param {*} date 当前时间
 */
function FormDate(date) {
  return `${date.getFullYear()}-${date.getMonth() + 1}-${date.getDate()} ${date.getHours()}:${date.getMinutes()}`
}
/**
 * 搭建一个服务器
 */
var server = http.createServer(function (res, res) {
  if (res.url !== '/favicon.ico') {
    res.writeHead(200, { "Content-type": "text/html" })
    const myreadstream = fs.createReadStream(__dirname + '/static/index.html', 'utf-8')
    myreadstream.pipe(res)
  }
})
//引入socket.io 这里是两步,第一步是io = require('socket.io') 第二步是一个新的变量.server 合成一步就是下面的代码
var io = require('socket.io')(server);
io.on("connection", function (socket) {
  //这里获取到对方的ip地址,可以展示,也可以不展示,也可以进行ip的过滤
  var clientIp = socket.request.connection.remoteAddress
  console.info("一个socket连接成功了")
  socket.on("link_to_server", function (msg, nick) {
    //这里使用io发送 
    io.emit('link_to_client', `${nick} : ${msg} ${FormDate(date)}`)
  })
})
server.listen(10010, '0.0.0.0');
console.info("server is running...")

下载socket.io 插件

 新建一个static文件夹并创建一个index.html文件


<!DOCTYPE html>
<html>
<head>
  <meta charset="utf-8">
  <title></title>
  <script src="/socket.io/socket.io.js"></script>
</head>
<body>
  <p>聊天室</p>
  <div id="infos">
  </div>
  <input style="margin-top: 5vh;
  width: 100px;
  height: 40px;
  border: 1px solid #ffffff;
  border-radius: 4px;
  color: #000000;
  padding-left: 10px" type="text" id="nick" value="" placeholder="昵称" />
  <input type="text" id="send_info" value="" placeholder="请输入您想说的话" />
  <button type="button" id="btn">发送</button>
</body>
<script>
  //创建一个io对象
  var socket = io();
  //用户点击发送的时候直接将昵称和信息内容发送过去,如果没有昵称,显示匿名,判断是不是有值
  document.getElementById("btn").onclick = function () {
    if(document.getElementById("send_info").value){
      socket.emit("link_to_server", document.getElementById("send_info").value, document.getElementById("nick").value ? document.getElementById("nick").value : '匿名')
    }else{
      alert(`发送内容不可以为空`)
    }
  }
  // 收到的信息展示出来,新建一个元素,append到div中
  socket.on('link_to_client', function (msg) {
    var h6 = document.createElement('h6');
    h6.innerText = `${msg}`;
    document.getElementById('infos').append(h6)
  })
</script>
<style>
  body {
    background: darkslateblue;
    text-align: center;
    color: aliceblue;
    margin: 0% 10%
  }
  p {
    font-size: 2rem
  }
  input {
    margin-top: 5vh;
    width: 200px;
    height: 40px;
    border: 1px solid #ffffff;
    border-radius: 4px;
    color: #000000;
    padding-left: 10px;
  }
  button {
    border: none;
    background: #ffffff;
    border-radius: 4px;
    width: 90px;
    height: 42px;
    color: #000000;
  }
  #infos {
    margin-left: 25vw;
    width: 400px;
    height: 500px;
    overflow: scroll;
    border: none;
    background: #ffffff;
    color: #000000;
  }
</style>
</html>

启动服务器 

 使用浏览器打开http://localhost:10010/index/html

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值