react实现简单的聊天功能以及后端代码
时间: 2023-12-11 09:04:36 浏览: 131
好的,下面我会提供一个简单的React聊天应用的后端代码和前端代码。
后端代码:
```javascript
const app = require('express')();
const http = require('http').createServer(app);
const io = require('socket.io')(http);
io.on('connection', (socket) => {
console.log('a user connected');
socket.on('sendMessage', (message) => {
console.log('message', message);
io.emit('newMessage', message);
});
socket.on('disconnect', () => {
console.log('user disconnected');
});
});
http.listen(3000, () => {
console.log('listening on *:3000');
});
```
这是一个基于Express和Socket.io的简单后端代码,监听3000端口,处理客户端发来的sendMessage事件,并将消息广播给所有在线用户。
前端代码:
```javascript
import React, { useState, useEffect, useRef } from 'react';
import io from 'socket.io-client';
const Chat = () => {
const [messages, setMessages] = useState([]);
const [message, setMessage] = useState('');
const [username, setUsername] = useState('');
const socketRef = useRef();
useEffect(() => {
// 连接Socket.io服务器
socketRef.current = io.connect('http://localhost:3000');
// 监听新消息
socketRef.current.on('newMessage', (message) => {
setMessages([...messages, message]);
});
return () => {
// 断开Socket.io连接
socketRef.current.disconnect();
};
}, [messages]);
const handleSubmit = (e) => {
e.preventDefault();
// 发送消息
socketRef.current.emit('sendMessage', { username, message });
// 清空消息框
setMessage('');
};
return (
<div>
<h1>Chat</h1>
<form onSubmit={handleSubmit}>
<input type="text" placeholder="Username" value={username} onChange={(e) => setUsername(e.target.value)} />
<input type="text" placeholder="Message" value={message} onChange={(e) => setMessage(e.target.value)} />
<button type="submit">Send</button>
</form>
<ul>
{messages.map((msg, index) => (
<li key={index}>
<strong>{msg.username}: </strong>
{msg.message}
</li>
))}
</ul>
</div>
);
};
export default Chat;
```
这是一个简单的React聊天组件,使用useState和useRef来管理状态和Socket.io连接,使用useEffect监听新消息并更新聊天记录列表。当用户发送消息时,调用handleSubmit函数发送消息到后端,后端将消息广播给所有在线用户。
阅读全文