简单聊天室socket.io使用nodejs搭建服务器

创建新的文件夹,打开终端初始化npm init -y
新建app.js.index.html文件
下包.npm i -S express socket.io
开启一个简单的聊天室

// nodejs 开启一个服务器

//导入模块/创建服务器
// const express = require('express')
// let app = express()
const app = require('express')()
// 创建一个http服务器对象,传入app
const http = require('http').createServer(app)
// 导入io
const io = require('socket.io')(http)

// 设置路由'/'
app.get('/', function(req, res) {
//指定HTTP头信息,将html转换中文,一般创建http设置在回调函数的参数的response中
  res.setHeader('Content-Type', 'text/html;charset=UTF-8')

  // res.end('终于连接上了吗?')
  // res.send('你好,世界')
  res.sendFile(__dirname + '/index.html')
})
// 添加连接
io.on('connection', socket => {
  console.log('有客户端连上了')

  socket.on('message', data => {
    console.log(data)
    // 服务器发送数据到浏览器
    socket.emit('serveMsg', data)
    // 聊天室广播,使用io.emit
    // io.emit('serveMsg',data)
  })
  // nodejs是单线程运行,异步操作使用回调函数返回值
  // disconnect会在打开服务器时从上到下运行时,连接后又断开,当发生数据命令后又连接断开
  // socket.on('disconnect', () => {
  //   console.log('连接断开了')
  // })
})

//3.开启服务器并监听端口3000
http.listen(3000, err => {
  if (err == null) {
    console.log('listening on 服务器开启成功*:3000')
  } else {
    console.log('服务器开启失败' + err.message)
  }
})

<!DOCTYPE html>
<html>
  <head>
    <title>Socket.IO chat</title>
    <style>
      * {
        margin: 0;
        padding: 0;
        box-sizing: border-box;
      }
      body {
        font: 13px Helvetica, Arial;
      }
      form {
        background: #000;
        padding: 3px;
        position: fixed;
        bottom: 0;
        width: 100%;
      }
      form input {
        border: 0;
        padding: 10px;
        width: 90%;
        margin-right: 0.5%;
      }
      form button {
        width: 9%;
        background: rgb(130, 224, 255);
        border: none;
        padding: 10px;
      }
      #messages {
        list-style-type: none;
        margin: 0;
        padding: 0;
      }
      #messages li {
        padding: 5px 10px;
      }
      #messages li:nth-child(odd) {
        background: #eee;
      }
    </style>
  </head>
  <body>
    <ul id="messages"></ul>
    <form action="">
      <input id="m" autocomplete="off" /><button>Send</button>
    </form>

    <script src="/socket.io/socket.io.js"></script>
    <script src="https://code.jquery.com/jquery-1.11.1.js"></script>
    <script>
      $(function() {
        // 创建io对象
        var socket = io('http://localhost:3000/')
        $('form').submit(function(e) {
          e.preventDefault()
          // 获取输入框内容
          console.log($('#m').val())
          // console.log(11111)
          // 将消息发送到服务器
          socket.emit('message', $('#m').val())
          // 清空input中消息
          $('#m').val('')
        })

        // 接收服务器消息,然后渲染页面
        socket.on('serveMsg', data => {
          // 将内容添加到ul标签中
          $('#messages').append($('<li>').text(data))
        })
      })
    </script>
  </body>
</html>

发布出去时,将浏览器端http://localhost:3000/的localhost改成ip地址

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值