用vue2来进行前后端websocket连接,实现简易聊天室

# 聊天室

  - 前端

    1. Login

       用户名输入 / 进入聊天室的按钮

       input username(6) -> localstorage -> enter the chatting room

    2. Home

       列表 / 消息输入框 / 发送按钮

       localstorage -> username / message / id / 消息时间 -> 后端socket服务

   

    open

    close

    error

    message  接收广播来的数据

  - 后端

       接收 -> 消息数据 -> 广播给所有连接到socket服务的客户端

    open

    close

    error

    connection

       message 接收客户端发送的消息数据 -> 广播


前端代码:

聊天框页面

<template>
  <div class="home">
    <ul>
      <li v-for="item of msgList" :key="item.id">
        <p class="red">
          <span>{{ item.user }}</span>
          <span>{{ new Date(item.dateTime) }}</span>
        </p>
        <p>消息:{{ item.msg }}</p>
      </li>
    </ul>

    <input type="text" placeholder="请输入消息" v-model="msg" class="inp" />
    <button class="btn" @click="handleSendBtnClick">发送</button>
  </div>
</template>

<script>
const ws = new WebSocket("ws://localhost:8000");

export default {
  name: "Home",
  data() {
    return {
      msg: "",
      username: "",
      msgList: [],
    };
  },
  mounted() {
    this.username = localStorage.getItem("username");

    if (!this.username) {
      this.$router.push("/login");
      return;
    }

    ws.addEventListener("open", this.handleWsOpen.bind(this), false);
    ws.addEventListener("close", this.handleWsClose.bind(this), false);
    ws.addEventListener("error", this.handleWsError.bind(this), false);
    ws.addEventListener("message", this.handleWsMessage.bind(this), false);
  },
  methods: {
    handleSendBtnClick() {
      const msg = this.msg;

      if (!msg.trim().length) {
        return;
      }

      ws.send(
        JSON.stringify({
          id: new Date().getTime(),
          user: this.username,
          dateTime: new Date().getTime(),
          msg: this.msg,
        })
      );

      this.msg = "";
    },
    handleWsOpen(e) {
      console.log("FE: WebSocket open", e);
    },
    handleWsClose(e) {
      console.log("FE: WebSocket close", e);
    },
    handleWsError(e) {
      console.log("FE: WebSocket error", e);
    },
    handleWsMessage(e) {
      const msg = JSON.parse(e.data);
      this.msgList.push(msg);
    },
  },
};
</script>

<style>
.red {
  color: red;
}

.btn {
  width: 100px;
  /* height: 50px; */
  background-color: rgb(12, 248, 158);
}
</style>

进入聊天框的页面

<template>
  <div class="about">
    <input type="text" placeholder="请输入用户名" v-model="username" />
    <button @click="handleEnterBtnClick">进入聊天室</button>
  </div>
</template>

<script>
  export default {
    name: 'Login',
    data () {
      return {
        username: ''
      }
    },
    mounted () {
      const username = localStorage.getItem('username');

      if (username) {
        this.$router.push('/');
        return;
      }
    },
    methods: {
      handleEnterBtnClick () {
        const username = this.username.trim();

        if (username.length < 6) {
          alert('用户名不小于6位');
          return;
        }

        localStorage.setItem('username', username);
        this.$router.push('/');
      }
    }
  }
</script>

后端代码:

const Ws = require('ws');

;((Ws) => {
  
  const server = new Ws.Server({ port: 8000 });


  const init = () => {
    bindEvent();
  }

  function bindEvent () {
    server.on('open', handleOpen);
    server.on('close', handleClose);
    server.on('error', handleError);
    server.on('connection', handleConnection);
  }

  function handleOpen () {
    console.log('open');
  }

  function handleClose () {
    console.log('close');
  }

  function handleError () {
    console.log('error');
  }

  function handleConnection (ws) {
    console.log('connection');

    ws.on('message', handleMessage);
  }

  function handleMessage (msg) {
    server.clients.forEach((c) => {
      c.send(msg);
    })
    console.log(msg)
  }

  init();
})(Ws);

  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值