gpt4 book ai didi

reactjs - socket.io 聊天问题与 react

转载 作者:行者123 更新时间:2023-12-05 07:12:28 25 4
gpt4 key购买 nike

我正在开发一个 create-react-app 项目,并试图整合一个由 sockets.io 提供支持的聊天控制台。问题在于,虽然聊天消息被前端正确捕获,发送回 io 服务器,然后发出,并且前端成功捕获了这些消息,但用户之间没有传递任何信息,一切都只是发生在单个浏览器实例上。在后端,当有人连接时,我有一个控制台记录“新客户端连接”。我注意到每次发送消息时控制台都会触发几次,这让我认为问题出在 react 重新渲染过程中的某个地方(因此重新渲染正在触发重新连接到套接字服务器。)

代码:

服务器:

const express = require("express");
const http = require("http");
const socketIo = require("socket.io");

const PORT = process.env.PORT || 4001;
const index = require("./routes/index");

const app = express();
app.use(index);

const server = http.createServer(app);

const io = socketIo(server);

io.on("connection", socket => {
console.log("New client connected");
socket.on("chat message", function(msg) {
console.log("message: " + msg);
socket.emit("chat message", [msg]);
});
socket.on("disconnect", () => console.log("Client disconnected"));
});

server.listen(PORT, () => console.log(`Listening on port ${PORT}`));

app.js(根组件)

import React, { useState, useEffect } from "react";
import "./App.css";
import Board from "./components/Board/Board";
import TileCard from "./components/TileCard/TileCard";
import Chat from "./components/Chat/Chat";
import Choice from "./components/Choice/Choice";
import Header from "./components/Header/Header";

import socketIOClient from "socket.io-client";

function App() {
const socket = socketIOClient("http://127.0.0.1:4001");
const [textValue, setTextValue] = useState("");
function handleChatSend(chatMsg) {
setTextValue(chatMsg);
socket.emit("chat message", chatMsg);
}

useEffect(() => {
socket.on("chat message", msg => {
setTextValue(msg);

console.log("receiving:" + msg);
});
}, [textValue]);

return (
<>
<Header />

<div className="content-container">
<Board />

<div className="cards-container col">
<Chat handleChatSend={handleChatSend} textValue={textValue} />
<TileCard />
<Choice />
</div>
</div>
</>
);
}

export default App;

聊天组件:

import React from 'react';
import "./chat.css"

function Chat ({handleChatSend, textValue}) {

return (
<div className="chatbox">
<ul id="messages">
{textValue !== "" ? <li>{textValue}</li> : null}
</ul>
<form onSubmit={event =>{
event.preventDefault();
let chatMsg = event.target.elements[0].value;
handleChatSend(chatMsg)}}>
<input type="text" id="m" autoComplete="off" /><button type="submit">Send</button>
</form>
</div>
)
}

export default Chat;

最佳答案

正如 Omer 在评论中提到的,我们需要使用 io 而不是 socket 发出事件,这就是我犯错的地方。在按照 Omer 的建议进行操作后,套接字就像神奇而真实的魔法发生了一样

这里是我如何从后端向客户端发出响应

export default function section(io: socketio.Server, socket: Socket) {
socket.on("update-section", async (payload: { [Key: string]: any }) => {
// const query: any = socket.handshake.query;
const updated = await updateSection({
...payload,
// ...decodeToken(query?.token),
});
io.emit(`update-section-response`, updated);
});

socket.on("delete-section", async (sectionId: string) => {
const deleted = await deleteSection(sectionId);
io.emit(`delete-section`, deleted);
});
}

关于reactjs - socket.io 聊天问题与 react ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60419488/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com