Warning: file_get_contents(/data/phpspider/zhask/data//catemap/3/reactjs/25.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/jquery-ui/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Reactjs socket.io聊天与react的问题_Reactjs_Socket.io_Chat_React Hooks - Fatal编程技术网

Reactjs socket.io聊天与react的问题

Reactjs socket.io聊天与react的问题,reactjs,socket.io,chat,react-hooks,Reactjs,Socket.io,Chat,React Hooks,我正在开发一个createreact应用程序项目,并试图整合一个由sockets.io提供电源的聊天控制台。问题在于,虽然聊天消息被前端正确捕获,发送回io服务器,然后发出,并且前端成功捕获了这些消息,但用户之间没有传递任何信息,一切只在单个浏览器实例上发生。 在后端,当有人连接时,我有一个控制台记录“新客户端已连接”。我注意到,每次发送消息时,控制台都会触发几次,这使我认为问题出在react重新呈现过程中的某个地方(因此重新呈现程序会触发与套接字服务器的重新连接) 守则: 服务器: const

我正在开发一个createreact应用程序项目,并试图整合一个由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,useffect}来自“React”;
导入“/App.css”;
从“/components/Board/Board”导入电路板;
从“/components/TileCard/TileCard”导入TileCard;
从“/components/Chat/Chat”导入聊天;
从“/components/Choice/Choice”导入选项;
从“/components/Header/Header”导入标题;
从“socket.io客户端”导入socketIOClient;
函数App(){
const socket=socketIOClient(“http://127.0.0.1:4001");
const[textValue,setTextValue]=useState(“”);
函数handleChatSend(chatMsg){
setTextValue(chatMsg);
发出(“聊天信息”,chatMsg);
}
useffect(()=>{
socket.on(“聊天信息”,msg=>{
setTextValue(msg);
控制台日志(“接收:+msg”);
});
},[textValue]);
返回(
);
}
导出默认应用程序;
聊天组件:

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; 
从“React”导入React;
导入“/chat.css”
函数聊天({handleChatSend,textValue}){
返回(
    {textValue!==“”?
  • {textValue}
  • :null}
{ event.preventDefault(); 让chatMsg=event.target.elements[0].value; handleChatSend(chatMsg)}> 发送 ) } 导出默认聊天;
正如Omer在评论中提到的,我们需要使用io而不是socket发出事件,这就是我犯错误的地方。按照Omer的建议进行操作后,它的工作原理就像是神奇的,真正的魔法发生在socket上

下面是我如何从后端向客户端发送响应

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);
  });
}

在server change
socket.emit(“聊天信息,[msg])中
io.emit(“聊天信息”,[msg])成功了!非常感谢你,我已经为此奋斗了好几个小时了…@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);
  });
}