当前位置: 首页 > 知识库问答 >
问题:

当用户不在聊天中时,如何显示发送的最后一条消息?

顾琛
2023-03-14

我目前有2个屏幕,一个所有的消息屏幕,其中包括我参与的所有聊天和一个聊天屏幕,这是实际的聊天本身。

在我的聊天屏幕中,我成功地实现了套接字,所以当两个用户同时在聊天屏幕上时,消息就会实时交换。

客户

ChatScreen.js

useEffect(() => {
const newsocket =io.connect("IP:PORT")
setMessages(message.Messages)

newsocket.on('connect', msg => {
console.log(`user: ${user.id} has joined conversation ${message.id}`)
setSocket(newsocket)
newsocket.emit('subscribe', message.id);
 });

newsocket.on("send_message", (msg) => {
console.log("this is the chat messages:", msg);
setMessages(messages => messages.concat(msg))
});

return(()=>newsocket.close());

}, []);

const onSend = (ConversationId,senderId,receiverId,message) => {
console.log("sent")
const to = (user.id===route.params.message.user1? 
route.params.message.user2:route.params.message.user1)
socket.emit('message', { to: to, from: user.id, message,ConversationId });
setText("")
messagesApi.sendMessage({ConversationId,senderId,receiverId,message});
};

AllMessagessCreen.js

const [posts, setPosts] = useState([]);
const [error, setError] = useState(false);
const [loading, setLoading] = useState(false);
const[page,setPage]=useState(0);
const [refreshing, setRefreshing] = useState(false);

const loadPosts = async () => {
setLoading(true);
const response = await messagesApi.getMessages();
setLoading(false);

if(refreshing) setRefreshing(false);

if (!response.ok) return setError(true);

setError(false);

setPosts(response.data)
};

useEffect(() => {
const unsubscribe = navigation.addListener('focus', () => {
loadPosts();
});
return unsubscribe;
}, [navigation]);

return(

<FlatList
    data={posts}
    keyExtractor={(post) => post.id.toString()}
    renderItem={({ item,index }) => (
      <MessagesList
      title={item.Post.title}
        subTitle={item.Messages[0].message}
        onPress={() => navigation.navigate(routes.CHAT,{message:item,index})}
      />
    )}
    refreshing={refreshing}
    onRefresh={() => {
      loadPosts()
    }}
  />
io.on('connection',(socket)=>{
console.log('User '+socket.id+' connected')

socket.on('subscribe', (room)=> {
console.log('joining room', room);
socket.join(room);
});

socket.on('message', (data) => {
console.log(data)
console.log('sending room post',data.ConversationId)
io.sockets.in(data.ConversationId).emit('send_message', { message: 
data.message, receiverId: 
data.to,senderId:data.from,conversationId:data.ConversationId });
})
})
useEffect(() => {
const newsocket =io.connect("IP:PORT")
setMessages(message.Messages)

newsocket.on('connect', msg => {
console.log(`user: ${user.id} has joined conversation ${message.id}`)
setSocket(newsocket)
newsocket.emit('subscribe', message.id);
 });

newsocket.on("send_message", (msg) => {
console.log("this is the chat messages:", msg);
setMessages(messages => messages.concat(msg))
});

return(()=>newsocket.close());

}, []);

const onSend = (ConversationId,senderId,receiverId,message) => {
console.log("sent")
const to = (user.id===route.params.message.user1? 
route.params.message.user2:route.params.message.user1)
socket.emit('message', { to: to, from: user.id, message,ConversationId });
setText("")
messagesApi.sendMessage({ConversationId,senderId,receiverId,message});
};
const [posts, setPosts] = useState([]);
const [error, setError] = useState(false);
const [loading, setLoading] = useState(false);
const[page,setPage]=useState(0);
const [refreshing, setRefreshing] = useState(false);

const loadPosts = async () => {
setLoading(true);
const response = await messagesApi.getMessages();
setLoading(false);

if(refreshing) setRefreshing(false);

if (!response.ok) return setError(true);

setError(false);

setPosts(response.data)
};

  useEffect(() => {
  const newsocket =io.connect("http://ip:port")
  loadPosts()

   newsocket.on('connect', msg => {
    console.log(`waiting for user: ${user.id} to join a conversation`) //this gets printed 
    setSocket(newsocket)
    newsocket.emit('waiting', user.id);
   });

 newsocket.on("send_message", (msg) => {
  console.log("this is the last message:", msg); //this doesnt get printed 
});
   }, []);

return(

<FlatList
    data={posts}
    keyExtractor={(post) => post.id.toString()}
    renderItem={({ item,index }) => (
      <MessagesList
      title={item.Post.title}
        subTitle={item.Messages[0].message}
        onPress={() => navigation.navigate(routes.CHAT,{message:item,index})}
      />
    )}
    refreshing={refreshing}
    onRefresh={() => {
      loadPosts()
    }}
  />
io.on('connection',(socket)=>{
console.log('User '+socket.id+' connected')//this gets printed 

socket.on('subscribe', (room)=> {
console.log('joining room', room);//this gets printed 
socket.join(room);
});

socket.on('message', (data) => {

console.log(data) //this gets printed 
console.log('sending room post',data.ConversationId) //this gets printed 
io.sockets.in(data.ConversationId).emit('send_message', { message: 
data.message, receiverId: 
data.to,senderId:data.from,conversationId:data.ConversationId }); 
})

socket.on('waiting', (user)=> {
console.log('user', user, 'is waiting.');//this gets printed 
});

})

共有1个答案

邓子濯
2023-03-14

我昨天也有同样的问题。但现在已经修好了。这个应该管用

import React, { useEffect, useState, useRef } from 'react'
import socket from 'socket.io-client'

const Chatbox = () => {
  const [chats, setChats] = useState([])
  const [message, setMessage] = useState('')
  const socketClientRef = useRef()

  useEffect(() => {
    const client = socket("http://localhost:3002");
    client.on("connect", () => {
      console.log('connected')
    })
    client.on("disconnect", () => {
      console.log('diconnected')
    });
    client.on("chat", message => {
      setChats(prevChats => [...prevChats, message])
      // INSTEAD OF:
      // setChats([...chats, message])
    });
    socketClientRef.current = client
    return () => {
      client.removeAllListeners()
    }
  }, [])

  const handleSend = async () => {
    socketClientRef.current.emit('chat', {
      room: `event-${eventId}`,
      message
    })
    setMessage('')
  }


  return (
    <div>
      <div>
        <h1>Messages</h1>
        {chats.map(chat => (
          <div>{chat}</div>
        ))}
      </div>
      <div>
        <input value={message} onChange={e => setMessage(e.target.value)} />
        <button onClick={handleSend}>Send</button>
      </div>
    </div>
  )
}
 类似资料:
  • 如何在聊天客户端发送媒体消息?我使用的是JS SDK,基于教程https://www.twilio.com/docs/api/chat/guides/media-support,但是出现了错误。我使用的方法如下所示: 错误消息:

  • 我的问题是,我仍然可以在客户端之间发送消息(客户端到客户端),但发送两三次后,消息不再显示给收件人。 因此,基本上每当客户机希望向另一个客户机发送消息时,该消息首先被发送到服务器。但正如您从我的编码中注意到的,我是以对象的形式发送服务器数据的。例如: 当您发送消息时,类型是“message”。当服务器接收对象时,它检查接收数据及其类型。例如: 如果类型是“message”,那么它会向特定的客户端发

  • 我正在尝试使用node.js、socket.io和express制作一个简单的聊天应用程序。但是,如果我单击main.jade文件中的send按钮,页面会刷新,并且不会出现任何消息。我在Firebug中也遇到这个错误: 加载页面时,与ws:/127.0.0.1:3000/socket.io/?eio=2&transport=websocket&sid=d_hnmpdxhed-j7lraaah的连接

  • 我想创建一个不和谐机器人,每天在特定的时间发送2条消息。下面的代码将使消息进入一个循环,例如每5秒发送一条消息。我如何设置每天发送消息的具体时间,例如,消息1在下午6点,消息2在上午10点。我在这里找到了这段代码,但是没有找到我想要的。

  • 所以我有一个Django应用程序,其中我使用频道来实现实时聊天。我的消费者看起来像这样: 导入json从asgiref.sync导入async_to_sync从channels.generic.websocket导入WebSocket消费者 因此,我正在寻找一种方法来保存发送的消息(因为当前它们在刷新时丢失)。我已经创建了一个消息模型,其中消息文本有一个CharField。如果我在聊天室信息功能中

  • 问题内容: 我想在用户连接到Spring WebSocket时向其发送消息, MyChannelInterception类为 通过这一点,我在收到新连接的用户,但该方法的信息中不将消息发送到新的登录用户。 问题答案: 我将创建侦听器并在内部使用。 顺便说一句,仅被调用一次(不适用于每个连接的用户)。因此,您必须处理拦截器中的发送消息。 尝试这样的事情: 我希望这个能帮上忙