koa+react+ts搭建简易聊天室

1.后端下包

npm i koa koa-websocket

2.后端代码

// 聊天室
const Koa = require("koa");
const WebSocket = require("koa-websocket");
const app = WebSocket(new Koa());
let ctxs = [];
// 简单的消息收发
app.ws.use((ctx, next) => {
  // 接收接入多个用户(每一个ctx代表一个用户)
  ctxs.push(ctx);
  ctx.websocket.on("message", (message) => {
    console.log(message, "message");
    for (let i = 0; i < ctxs.length; i++) {
      if (ctx == ctxs[i]) continue;
      ctxs[i].websocket.send(message.toString());
    }
  });
  ctx.websocket.on("close", (message) => {
    // 关闭时清除相关数据,防止出错
    let index = ctxs.indexOf(ctx);
    ctxs.splice(index, 1);
  });
});
app.listen(3001, () => console.log("http://localhost:3001"));

3.前端代码

html页面

import React from 'react'
import './index.moudle.scss'
import NavBar from '@/components/navBar';

//实例化 WebSocket 并且连接服务器
const webSocket = new WebSocket("ws://localhost:3001");

/* 接收到服务端的消息时 */
webSocket.onmessage = function (msg) {
    console.log("接收到新消息:" + msg.data);
    const oFriendItem = document.createElement('div');
    oFriendItem.className = 'friedns-item';
    const oSpan = document.createElement('span');
    oSpan.className = 'friedns';
    const message = document.createTextNode(msg.data);
    oSpan.appendChild(message);
    oFriendItem.appendChild(oSpan);
    (document.getElementById('chatContent') as HTMLElement).appendChild(oFriendItem);
};

// 关闭连接
webSocket.onclose = function () {
    console.log("关闭连接");
};

function Socket() {
    // 发送
    const sendBtn = () => {
        const str = (document.getElementById('content') as HTMLInputElement).value
        const oMeItem = document.createElement('div');
        oMeItem.className = 'me-item';
        const oSpan = document.createElement('span');
        oSpan.className = 'me';
        const msg = document.createTextNode((document.getElementById('content') as HTMLInputElement).value);
        oSpan.appendChild(msg);
        oMeItem.appendChild(oSpan);
        (document.getElementById('chatContent') as HTMLElement).appendChild(oMeItem);
        // 发送后清空消息框
        (document.getElementById('content') as HTMLInputElement).value = '';
        webSocket.send(str);
    }

    // 关闭连接
    const closeBtn = () => {
        webSocket.close();
    }

    return (
        <div className="chat-room">
            <NavBar title='聊天室' type='back' />
            <div className="chat-content" id="chatContent">
            </div>
            <div className="chat-op">
                <input type="text" id="content" />
                <input type="button" value="发送" onClick={sendBtn} id="send" />
                <input type="button" value="关闭" onClick={closeBtn} id="close" />
            </div>

        </div>
    )
}

export default Socket
 .chat-room {
     width: 100%;
     height: 100%;
     display: flex;
     flex-direction: column;
 }

 .chat-content {
     width: 100%;
     flex: 1;
     background: #eee;
     overflow: auto;
 }

 .chat-op {
     width: 100%;
     height: 40px;
     line-height: 40px;
     position: fixed;
     bottom: 0;
     left: 0;
 }

 .me-item {
     text-align: right;
 }

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值