当前位置: 代码网 > 服务器>网络>https > react中使用 websocket

react中使用 websocket

2024年08月03日 https 我要评论
参考官网地址: https://socket.io/zh-CN/docs/v4/client-installation/#from-npm。react中使用 websocket,使用socket.io库。

下方是我微信公众号的二维码,关于react及其他相关知识点会在公众号上面更新,可以扫码关注以下,有什么问题也可以通过公众号跟我留言哦

在这里插入图片描述

react中使用 websocket,使用socket.io库
参考官网地址: https://socket.io/zh-cn/docs/v4/client-installation/#from-npm

1.安装

npm install socket.io-client

2.示例代码

import react, { useeffect, useref, usestate } from "react";
import classnames from "classnames";
import { formatdate } from "../../utils/format";
import "./index.css";

// https://socket.io/zh-cn/docs/v4/client-installation/#from-npm
import { io } from "socket.io-client";
const socket = io("ws://localhost:8888"); // 连接,握手

function chat() {
  // 用户列表
  const [userslist, setuserslist] = usestate([]);
  // 历史记录
  const [historydata, sethistorydata] = usestate([]);
  // 当前用户是否是自己
  const [mine, setmine] = usestate("");
  // 要发送的消息
  const [message, setmessage] = usestate("");

  useeffect(() => {
    // 当前聊天室的用户数组 -- 有新用户进入/老用户退出/自己进入
    socket.on("$updateuser", (users) => {
      console.log(users, "users");
      setuserslist(users);
    });
    // 分配的用户名称 -- 自己进入
    socket.on("$name", (name) => {
      console.log(name, "name");
      setmine(name);
    });
    // 历史聊天记录  -- 自己进入
    socket.on("$history", (history) => {
      console.log(history, "history");
      sethistorydata(history);
    });
    // 其他人发送消息
    socket.on("$message", (message) => {
      console.log(message, 123);
      sethistorydata([...historydata, message]);
    });
    return () => {
      socket.off("$updateuser");
      socket.off("$name");
      socket.off("$history");
      socket.off("$message");
    };
  }, [historydata]);

  const chatarearef = useref();
  //  当聊天区高度超出后,设置滚动条在最下面
  useeffect(() => {
    chatarearef.current.scrolltop = chatarearef.current.scrollheight;
  }, [historydata]);

  //   发送消息
  const handlekeydown = (e) => {
    if (e.key === "enter") {
      e.preventdefault(); // 阻止默认的换行行为
      const content = message.trim();
      if (!content) return;
      const messageinfo = {
        name: mine,
        content: content,
        data: date.now(),
      };
      sethistorydata([...historydata, messageinfo]); // 将消息添加到历史记录里面
      socket.emit("$message", message); // 将消息发送到服务器
      setmessage(""); // 清空textarea
    }
  };

  return (
    <section classname="chat-container">
      <aside classname="chat-users">
        <div classname="title">聊天室成员</div>
        {userslist.length > 0 &&
          userslist.map((item, index) => (
            <div key={index} classname="per-user">
              {item}
            </div>
          ))}
      </aside>
      <section classname="chat-main">
        <div classname="chat-user">{mine}</div>
        <div classname="chat-area" ref={chatarearef}>
          {historydata.length > 0 &&
            historydata.map((item, index) => (
              <div
                key={index}
                classname={classnames("chat-item", {
                  mine: mine === item.name,
                })}
              >
                <div classname="name">{item.name}</div>
                <div classname="content">{item.content}</div>
                <div classname="date">{formatdate(item.date)}</div>
              </div>
            ))}
        </div>
        <div classname="chat-message">
          <textarea
            name="message"
            value={message}
            onchange={(e) => {
              setmessage(e.target.value);
            }}
            onkeydown={handlekeydown}
          ></textarea>
        </div>
      </section>
    </section>
  );
}

export default chat;

3.效果:
在这里插入图片描述

(0)

相关文章:

版权声明:本文内容由互联网用户贡献,该文观点仅代表作者本人。本站仅提供信息存储服务,不拥有所有权,不承担相关法律责任。 如发现本站有涉嫌抄袭侵权/违法违规的内容, 请发送邮件至 2386932994@qq.com 举报,一经查实将立刻删除。

发表评论

验证码:
Copyright © 2017-2025  代码网 保留所有权利. 粤ICP备2024248653号
站长QQ:2386932994 | 联系邮箱:2386932994@qq.com