聊天室(socket.io)

237 阅读1分钟

使用websoket.io工具,实现一个简单的聊天室。

服务端发送信息:

  • io.emit()向所有连接的用户,进行广播
  • socket.broadcast.emit('hi');向除了发送者以外的用户广播
  • socket.emit('hi'); 向发送者自己广播数据

以下代码以react的写法举例:

服务端代码:

const express = require("express");
const app = express();
const http = require("http");
const httpServer = http.createServer();
const { Server } = require("socket.io");
const io = new Server(httpServer, {
  path: "/websorket/",
  //处理跨域问题
  cors: {
    origin: ["http://localhost:3000"],
    allowedHeaders: ["my-custom-header"],
    credentials: true,
  },
});
//将前端页面放在服务器上
// app.get('/', (req, res) => {
//   res.sendFile(__dirname + '/index.html');
// });
io.on("connection", (socket) => {
  socket.on("msg:start", (id) => {
    console.log("服务器接收到,id", id);
    io.emit("msg:add", {
      [id]: `用户${id}已上线`,
    });
  });
  socket.on("cs", function (id, msg) {
    //除了自身以外的人发送
    io.emit("ss", {
      id,
      msg: msg,
    });
  });
});

httpServer.listen(8088, () => {
  console.log("listening on *:8088");
});

客户端代码:

import { useEffect, useState } from "react";
import { io } from "socket.io-client";

import { Button, Input, Select, Space } from "antd";
let socket;
let id;
export default function Chat() {
  const [chat, setChat] = useState();
  const [chatList, setChatList] = useState([]);

  const inputSend = () => {
    // //向服务端发送消息
    socket.emit("cs", id, chat);
    setChat("");
  };

  const inputChange = (event, val) => {
    let curVal = val || event.target.value;
    setChat(curVal);
  };
  useEffect(() => {
    id = `id_${parseInt(Math.random() * 1000)}`;
    socket = io("ws://localhost:8088", {
      path: "/websorket/",
      randomizationFactor: 10000,
      query: {
        x: 42,
      },
    });
    //连接
    // socket.on("connect", function (res) {
    socket.emit("msg:start", id);
    // });

    socket.on("ss", (arg) => {
      console.log(arg);
      console.log(chatList);
      //   let list=chatList.concat(arg)
      //   setChatList(list)
      setChatList((list) => [...list, arg]);
    });

    socket.on("msg:add", (data) => {
      console.log(id);
      console.log(data);
      data && (data[id] || console.log(`上线通知:${JSON.stringify(data)}`));
    });

    return () => {
      socket.disconnect();
    };
  }, []);
  return (
    <div className="bg-gray-200">
      <h2>聊天室</h2>
      <div className="h-60">
        {chatList.map((item, idx) => (
          <div
            key={idx}
            className={item.id === id ? "text-right mb-3" : "text-left mb-3"}
          >
            <span
              className={[
                item.id === id
                  ? "bg-blue-400 text-white "
                  : " bg-yellow-400 text-white ",
                "inline-block rounded-lg px-5",
              ]}
            >
              {item.id === id ? item.msg : `${item.id}说:${item.msg}`}
            </span>
          </div>
        ))}
      </div>
      <Space.Compact
        style={{
          width: "100%",
        }}
      >
        <Input value={chat} onChange={inputChange} />
        <Button type="primary" onClick={inputSend}>
          Submit
        </Button>
      </Space.Compact>
    </div>
  );
}

使用工具文档参考:

socket.io/