鱼C论坛

 找回密码
 立即注册
查看: 2637|回复: 2

[已解决]给你一个聊天服务器,如何连入创建聊天室?

[复制链接]
发表于 2020-11-8 09:31:50 | 显示全部楼层 |阅读模式

马上注册,结交更多好友,享用更多功能^_^

您需要 登录 才可以下载或查看,没有账号?立即注册

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




   大佬们走过路过不要弃之不理啊!!!
最佳答案
2023-7-22 08:54:06
可以使用 Create React App 来初始化 Reac t应用程序,并使用 yarn 来管理依赖。

在初始化应用程序后使用:

  • Ant Design的List组件来显示聊天消息
  • Redux Toolkit来管理状态
  • createSlice创建Redux的reducer和action
  • thunk来处理异步操作
  • axios库发送和接收数据




以下是代码示例:

首先,确保已经安装了Create React App和yarn。然后,在终端中执行以下命令:

  1. npx create-react-app chat-app
  2. cd chat-app
  3. yarn add antd redux react-redux @reduxjs/toolkit axios
复制代码

然后,将 "src/App.js" 文件的内容替换为以下代码:

  1. import React, { useEffect } from 'react';
  2. import { List } from 'antd';
  3. import { useSelector, useDispatch } from 'react-redux';
  4. import { createSlice, configureStore, createAsyncThunk, createAction } from '@reduxjs/toolkit';
  5. import axios from 'axios';

  6. const initialState = {
  7.   messages: [],
  8.   loading: false,
  9.   error: null,
  10. };

  11. const chatSlice = createSlice({
  12.   name: 'chat',
  13.   initialState,
  14.   reducers: {
  15.     addMessage: (state, action) => {
  16.       state.messages.push(action.payload);
  17.     },
  18.     setLoading: (state, action) => {
  19.       state.loading = action.payload;
  20.     },
  21.     setError: (state, action) => {
  22.       state.error = action.payload;
  23.     },
  24.   },
  25. });

  26. export const { addMessage, setLoading, setError } = chatSlice.actions;

  27. export const fetchMessages = createAsyncThunk('chat/fetchMessages', async () => {
  28.   try {
  29.     const response = await axios.get('http://loriame.cn:5000/ailab/getMessages');
  30.     return response.data;
  31.   } catch (error) {
  32.     throw Error('Failed to fetch messages');
  33.   }
  34. });

  35. export const sendMessage = createAsyncThunk('chat/sendMessage', async (message) => {
  36.   try {
  37.     const response = await axios.post('http://loriame.cn:5000/ailab/sendMessage', message, {
  38.       headers: { 'Content-Type': 'application/json' },
  39.     });
  40.     return response.data;
  41.   } catch (error) {
  42.     throw Error('Failed to send message');
  43.   }
  44. });

  45. const reducer = chatSlice.reducer;

  46. const store = configureStore({
  47.   reducer,
  48. });

  49. const ChatApp = () => {
  50.   const dispatch = useDispatch();
  51.   const messages = useSelector((state) => state.messages);
  52.   const loading = useSelector((state) => state.loading);
  53.   const error = useSelector((state) => state.error);

  54.   useEffect(() => {
  55.     dispatch(fetchMessages());
  56.   }, [dispatch]);

  57.   const handleSendMessage = (name, message) => {
  58.     dispatch(setLoading(true));
  59.     dispatch(setError(null));

  60.     dispatch(
  61.       sendMessage({ name, message })
  62.     ).unwrap()
  63.       .then(() => {
  64.         dispatch(fetchMessages());
  65.       })
  66.       .catch((error) => {
  67.         dispatch(setError(error.message));
  68.       })
  69.       .finally(() => {
  70.         dispatch(setLoading(false));
  71.       });
  72.   };

  73.   return (
  74.     <div>
  75.       {loading && <div>Loading...</div>}
  76.       {error && <div>Error: {error}</div>}
  77.       <List
  78.         dataSource={messages}
  79.         renderItem={({ name, message }) => (
  80.           <List.Item>
  81.             <List.Item.Meta title={name} description={message} />
  82.           </List.Item>
  83.         )}
  84.       />
  85.     </div>
  86.   );
  87. };

  88. const App = () => {
  89.   return (
  90.     <Provider store={store}>
  91.       <ChatApp />
  92.     </Provider>
  93.   );
  94. };

  95. export default App;
复制代码

我们首先定义了初始状态、Redux的reducer和action,以及异步操作thunk。

在ChatApp组件中,我们使用useSelector和useDispatch来获取Redux store中的状态和派发action。在组件的useEffect钩子函数中,我们调用fetchMessages来获取聊天消息。当发送消息时,我们调用sendMessage来异步发送消息,并更新聊天消息。

最后,我们将应用程序包装在Provider组件中,以便Redux store能够在整个应用程序中共享。


想知道小甲鱼最近在做啥?请访问 -> ilovefishc.com
回复

使用道具 举报

发表于 2020-11-21 13:40:22 | 显示全部楼层
老哥,发代码的时候用代码格式,这样看着真的头疼,没有看全,但是我觉得做聊天室,应该是即时通讯,应该是用  socket实现,而不是ajax
想知道小甲鱼最近在做啥?请访问 -> ilovefishc.com
回复 支持 反对

使用道具 举报

发表于 2023-7-22 08:54:06 | 显示全部楼层    本楼为最佳答案   
可以使用 Create React App 来初始化 Reac t应用程序,并使用 yarn 来管理依赖。

在初始化应用程序后使用:

  • Ant Design的List组件来显示聊天消息
  • Redux Toolkit来管理状态
  • createSlice创建Redux的reducer和action
  • thunk来处理异步操作
  • axios库发送和接收数据




以下是代码示例:

首先,确保已经安装了Create React App和yarn。然后,在终端中执行以下命令:

  1. npx create-react-app chat-app
  2. cd chat-app
  3. yarn add antd redux react-redux @reduxjs/toolkit axios
复制代码

然后,将 "src/App.js" 文件的内容替换为以下代码:

  1. import React, { useEffect } from 'react';
  2. import { List } from 'antd';
  3. import { useSelector, useDispatch } from 'react-redux';
  4. import { createSlice, configureStore, createAsyncThunk, createAction } from '@reduxjs/toolkit';
  5. import axios from 'axios';

  6. const initialState = {
  7.   messages: [],
  8.   loading: false,
  9.   error: null,
  10. };

  11. const chatSlice = createSlice({
  12.   name: 'chat',
  13.   initialState,
  14.   reducers: {
  15.     addMessage: (state, action) => {
  16.       state.messages.push(action.payload);
  17.     },
  18.     setLoading: (state, action) => {
  19.       state.loading = action.payload;
  20.     },
  21.     setError: (state, action) => {
  22.       state.error = action.payload;
  23.     },
  24.   },
  25. });

  26. export const { addMessage, setLoading, setError } = chatSlice.actions;

  27. export const fetchMessages = createAsyncThunk('chat/fetchMessages', async () => {
  28.   try {
  29.     const response = await axios.get('http://loriame.cn:5000/ailab/getMessages');
  30.     return response.data;
  31.   } catch (error) {
  32.     throw Error('Failed to fetch messages');
  33.   }
  34. });

  35. export const sendMessage = createAsyncThunk('chat/sendMessage', async (message) => {
  36.   try {
  37.     const response = await axios.post('http://loriame.cn:5000/ailab/sendMessage', message, {
  38.       headers: { 'Content-Type': 'application/json' },
  39.     });
  40.     return response.data;
  41.   } catch (error) {
  42.     throw Error('Failed to send message');
  43.   }
  44. });

  45. const reducer = chatSlice.reducer;

  46. const store = configureStore({
  47.   reducer,
  48. });

  49. const ChatApp = () => {
  50.   const dispatch = useDispatch();
  51.   const messages = useSelector((state) => state.messages);
  52.   const loading = useSelector((state) => state.loading);
  53.   const error = useSelector((state) => state.error);

  54.   useEffect(() => {
  55.     dispatch(fetchMessages());
  56.   }, [dispatch]);

  57.   const handleSendMessage = (name, message) => {
  58.     dispatch(setLoading(true));
  59.     dispatch(setError(null));

  60.     dispatch(
  61.       sendMessage({ name, message })
  62.     ).unwrap()
  63.       .then(() => {
  64.         dispatch(fetchMessages());
  65.       })
  66.       .catch((error) => {
  67.         dispatch(setError(error.message));
  68.       })
  69.       .finally(() => {
  70.         dispatch(setLoading(false));
  71.       });
  72.   };

  73.   return (
  74.     <div>
  75.       {loading && <div>Loading...</div>}
  76.       {error && <div>Error: {error}</div>}
  77.       <List
  78.         dataSource={messages}
  79.         renderItem={({ name, message }) => (
  80.           <List.Item>
  81.             <List.Item.Meta title={name} description={message} />
  82.           </List.Item>
  83.         )}
  84.       />
  85.     </div>
  86.   );
  87. };

  88. const App = () => {
  89.   return (
  90.     <Provider store={store}>
  91.       <ChatApp />
  92.     </Provider>
  93.   );
  94. };

  95. export default App;
复制代码

我们首先定义了初始状态、Redux的reducer和action,以及异步操作thunk。

在ChatApp组件中,我们使用useSelector和useDispatch来获取Redux store中的状态和派发action。在组件的useEffect钩子函数中,我们调用fetchMessages来获取聊天消息。当发送消息时,我们调用sendMessage来异步发送消息,并更新聊天消息。

最后,我们将应用程序包装在Provider组件中,以便Redux store能够在整个应用程序中共享。


想知道小甲鱼最近在做啥?请访问 -> ilovefishc.com
回复 支持 反对

使用道具 举报

您需要登录后才可以回帖 登录 | 立即注册

本版积分规则

小黑屋|手机版|Archiver|鱼C工作室 ( 粤ICP备18085999号-1 | 粤公网安备 44051102000585号)

GMT+8, 2024-4-20 14:25

Powered by Discuz! X3.4

© 2001-2023 Discuz! Team.

快速回复 返回顶部 返回列表