给你一个聊天服务器,如何连入创建聊天室?
function getMessage() { var res = null; var ajax = new XMLHttpRequest(); ajax.open('get', 'http://loriame.cn:5000/ailab/getMessages', false); ajax.send(); if (ajax.readyState == 4 && ajax.status == 200) { res =JSON.parse(ajax.responseText); } return res;}
// 获取全部留言数据
function getAllMessage() { var res = null; var ajax = new XMLHttpRequest(); ajax.open('get', 'http://loriame.cn:5000/ailab/getAllMessage', false); ajax.send(); if (ajax.readyState == 4 && ajax.status == 200) { res = JSON.parse(ajax.responseText); } return res;}
// 发送一条留言
function sendMessage(name, message) { var res = null; var ajax = new XMLHttpRequest(); ajax.open('post', 'http://loriame.cn:5000/ailab/sendMessage', false); ajax.setRequestHeader("Content-Type", 'application/json');
//设置请求头
ajax.send(JSON.stringify({name, message})); if (ajax.readyState == 4 && ajax.status == 200) { res = JSON.parse(ajax.responseText); }
return res;}
var backTime = getMessage();
console.log(backTime);
var backTimeMessage = getMessage();
console.log(backTimeMessage);
大佬们走过路过不要弃之不理啊!!! {:5_104:} 老哥,发代码的时候用代码格式,这样看着真的头疼,没有看全,但是我觉得做聊天室,应该是即时通讯,应该是用socket实现,而不是ajax 可以使用 Create React App 来初始化 Reac t应用程序,并使用 yarn 来管理依赖。
在初始化应用程序后使用:
[*]Ant Design的List组件来显示聊天消息
[*]Redux Toolkit来管理状态
[*]createSlice创建Redux的reducer和action
[*]thunk来处理异步操作
[*]axios库发送和接收数据
以下是代码示例:
首先,确保已经安装了Create React App和yarn。然后,在终端中执行以下命令:
npx create-react-app chat-app
cd chat-app
yarn add antd redux react-redux @reduxjs/toolkit axios
然后,将 "src/App.js" 文件的内容替换为以下代码:
import React, { useEffect } from 'react';
import { List } from 'antd';
import { useSelector, useDispatch } from 'react-redux';
import { createSlice, configureStore, createAsyncThunk, createAction } from '@reduxjs/toolkit';
import axios from 'axios';
const initialState = {
messages: [],
loading: false,
error: null,
};
const chatSlice = createSlice({
name: 'chat',
initialState,
reducers: {
addMessage: (state, action) => {
state.messages.push(action.payload);
},
setLoading: (state, action) => {
state.loading = action.payload;
},
setError: (state, action) => {
state.error = action.payload;
},
},
});
export const { addMessage, setLoading, setError } = chatSlice.actions;
export const fetchMessages = createAsyncThunk('chat/fetchMessages', async () => {
try {
const response = await axios.get('http://loriame.cn:5000/ailab/getMessages');
return response.data;
} catch (error) {
throw Error('Failed to fetch messages');
}
});
export const sendMessage = createAsyncThunk('chat/sendMessage', async (message) => {
try {
const response = await axios.post('http://loriame.cn:5000/ailab/sendMessage', message, {
headers: { 'Content-Type': 'application/json' },
});
return response.data;
} catch (error) {
throw Error('Failed to send message');
}
});
const reducer = chatSlice.reducer;
const store = configureStore({
reducer,
});
const ChatApp = () => {
const dispatch = useDispatch();
const messages = useSelector((state) => state.messages);
const loading = useSelector((state) => state.loading);
const error = useSelector((state) => state.error);
useEffect(() => {
dispatch(fetchMessages());
}, );
const handleSendMessage = (name, message) => {
dispatch(setLoading(true));
dispatch(setError(null));
dispatch(
sendMessage({ name, message })
).unwrap()
.then(() => {
dispatch(fetchMessages());
})
.catch((error) => {
dispatch(setError(error.message));
})
.finally(() => {
dispatch(setLoading(false));
});
};
return (
<div>
{loading && <div>Loading...</div>}
{error && <div>Error: {error}</div>}
<List
dataSource={messages}
renderItem={({ name, message }) => (
<List.Item>
<List.Item.Meta title={name} description={message} />
</List.Item>
)}
/>
</div>
);
};
const App = () => {
return (
<Provider store={store}>
<ChatApp />
</Provider>
);
};
export default App;
我们首先定义了初始状态、Redux的reducer和action,以及异步操作thunk。
在ChatApp组件中,我们使用useSelector和useDispatch来获取Redux store中的状态和派发action。在组件的useEffect钩子函数中,我们调用fetchMessages来获取聊天消息。当发送消息时,我们调用sendMessage来异步发送消息,并更新聊天消息。
最后,我们将应用程序包装在Provider组件中,以便Redux store能够在整个应用程序中共享。
页:
[1]