Привет. Скажите пожалуйста в чём может быть причина такого поведения? Пишу чат, взял исходник фронта на реакте с гита. Дописал к нему сокет для чата, но он работает не так как я хотел бы.
Фронт с гита
Back:
const app = require("express")();
const httpServer = require("http").createServer(app);
const options = {
cors: {
origin: "*",
methods: ["GET", "POST"]
}
};
const io = require("socket.io")(httpServer, options);
io.on("connection", socket => {
console.log(socket.id);
socket.on('disconnect', () => {
console.log('user disconnected');
});
socket.on('message', message => {
io.emit('showMessage', message);
});
});
app.get('/', (req, res) => {
res.send({data: 'Okay'}).status(200);
});
httpServer.listen(4001);
Component:
import React, {useEffect, useState} from 'react';
import Compose from '../Compose';
import Toolbar from '../Toolbar';
import ToolbarButton from '../ToolbarButton';
import Message from '../Message';
import moment from 'moment';
import './MessageList.css';
import socketIOClient from "socket.io-client";
const ENDPOINT = "http://localhost:4001/";
const socket = socketIOClient(ENDPOINT);
export default function MessageList(props) {
const [messages, setMessages] = useState([]);
const tempMessages = [];
useEffect(() => {
socket.on("connect", () => {
console.log(socket.id);
});
socket.on('showMessage', message => {
tempMessages.push(
{
id: Math.random(),
author: socket.id,
message: message,
timestamp: new Date().getTime()
}
);
getMessages(tempMessages);
console.log(tempMessages);
});
},[]);
const getMessages = (msg) => {
setMessages([...messages, ...msg]);
}
const renderMessages = () => {
let i = 0;
let messageCount = messages.length;
let tempMessages = [];
while (i < messageCount) {
let previous = messages[i - 1];
let current = messages[i];
let next = messages[i + 1];
let isMine = current.author === socket.id;
let currentMoment = moment(current.timestamp);
let prevBySameAuthor = false;
let nextBySameAuthor = false;
let startsSequence = true;
let endsSequence = true;
let showTimestamp = true;
if (previous) {
let previousMoment = moment(previous.timestamp);
let previousDuration = moment.duration(currentMoment.diff(previousMoment));
prevBySameAuthor = previous.author === current.author;
if (prevBySameAuthor && previousDuration.as('hours') < 1) {
startsSequence = false;
}
if (previousDuration.as('hours') < 1) {
showTimestamp = false;
}
}
if (next) {
let nextMoment = moment(next.timestamp);
let nextDuration = moment.duration(nextMoment.diff(currentMoment));
nextBySameAuthor = next.author === current.author;
if (nextBySameAuthor && nextDuration.as('hours') < 1) {
endsSequence = false;
}
}
tempMessages.push(
<Message
key={i}
isMine={isMine}
startsSequence={startsSequence}
endsSequence={endsSequence}
showTimestamp={showTimestamp}
data={current}
/>
);
// Proceed to the next message.
i += 1;
}
return tempMessages;
}
return(
<div className="message-list">
<Toolbar
title="Messanger"
rightItems={[
<ToolbarButton key="info" icon="ion-ios-information-circle-outline" />,
<ToolbarButton key="video" icon="ion-ios-videocam" />,
<ToolbarButton key="phone" icon="ion-ios-call" />
]}
/>
<div className="message-list-container">{renderMessages()}</div>
<Compose rightItems={[
<ToolbarButton key="photo" icon="ion-ios-camera" />,
<ToolbarButton key="image" icon="ion-ios-image" />,
<ToolbarButton key="audio" icon="ion-ios-mic" />,
<ToolbarButton key="money" icon="ion-ios-card" />,
<ToolbarButton key="games" icon="ion-logo-game-controller-b" />,
<ToolbarButton key="emoji" icon="ion-ios-happy" />
]}/>
</div>
);
}
Он присвает сокет id текущего клиента при отправке сообщений, всем сообщениям. Как это исправить?
0: {id: 0.8027327004825733, author: "eknt9RjpM07f6LPcAACQ", message: "asdasd", timestamp: 1624483588783}
1: {id: 0.6056099262860521, author: "eknt9RjpM07f6LPcAACQ", message: "asdasd", timestamp: 1624483589690}
2: {id: 0.11380354097618484, author: "eknt9RjpM07f6LPcAACQ", message: "asdasd", timestamp: 1624483589925}
3: {id: 0.03147155705252702, author: "eknt9RjpM07f6LPcAACQ", message: "asdasd", timestamp: 1624483590080}
4: {id: 0.3803585117922945, author: "eknt9RjpM07f6LPcAACQ", message: "asdasd", timestamp: 1624483590213}
5: {id: 0.44360424240870655, author: "eknt9RjpM07f6LPcAACQ", message: "asdasd", timestamp: 1624483598541}
6: {id: 0.5698285704409161, author: "eknt9RjpM07f6LPcAACQ", message: "asdasd", timestamp: 1624483599119}
7: {id: 0.4798664574785938, author: "eknt9RjpM07f6LPcAACQ", message: "asdasd", timestamp: 1624483599277}
8: {id: 0.13681540277126292, author: "eknt9RjpM07f6LPcAACQ", message: "asdasd", timestamp: 1624483599408}
length: 9
__proto__: Array(0)
Спасибо.