页: 1 为了建造聊天室,但当输入信息时,只有其他用户看到电文时,作者们看不到任何东西,而其他信息如上面的形象。 这是我的法典:
const express = require("express");
const app = express();
const PORT = 4000;
//New imports
const http = require("http");
const cors = require("cors");
const { Server } = require("socket.io");
const server = http.createServer(app);
const io = new Server(server, {
cors: {
origin: "http://localhost:3000",
methods: ["GET", "POST"],
},
});
io.on("connection", (socket) => {
console.log(`⚡: ${socket.id} user just connected!`);
socket.on("join_room", (data) => {
socket.join( 123 );
});
socket.on("send_message", (data) => {
socket.to( 123 ).emit("receive_message", `${socket.id}: ${data}`);
});
socket.on("disconnect", () => {
console.log("?: A user disconnected");
});
});
app.use(cors());
server.listen(PORT, () => {
console.log(`Server listening on ${PORT}`);
});
And front end
import React, { useState, useEffect } from react ;
import { ConnectionState } from ./components/ConnectionState ;
import { ConnectionManager } from ./components/ConnectionManager ;
import { MyForm } from ./components/MyForm ;
import { socket } from ./socket ;
import { Events } from ./components/Events ;
import { Button } from @mui/material ;
export default function App() {
const [isConnected, setIsConnected] = useState(socket.connected);
const [fooEvents, setFooEvents] = useState<any>([]);
const [joinRoom, setJoinRoom] = useState<{
name: string;
room: string;
time: Date;
}>();
function onJoinRoom() {
socket.emit( join_room , 123 );
}
useEffect(() => {
function onConnect() {
setIsConnected(true);
}
function onDisconnect() {
setIsConnected(false);
}
socket.on( connect , onConnect);
socket.on( disconnect , onDisconnect);
return () => {
socket.off( connect , onConnect);
socket.off( disconnect , onDisconnect);
};
}, []);
useEffect(() => {
function onFooEvent(value: any) {
setFooEvents((previous: any) => [...previous, value]);
}
socket.on( receive_message , onFooEvent);
return () => {
socket.off( receive_message , onFooEvent);
};
}, [socket]);
return (
<div className="App">
<ConnectionState isConnected={isConnected} />
<Events events={fooEvents} />
<Button onClick={onJoinRoom}>Join Room</Button>
<ConnectionManager />
<MyForm />
</div>
);
}
连接国是一个不付钱的连接状态,事件是,信息显示、只有阵列、联系管理人通连接的纽伦,我的表格是输入信息并提交。