React Native、NodeJS、Socket.io [英] React Native, NodeJS, Socket.io

查看:46
本文介绍了React Native、NodeJS、Socket.io的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试在我的应用程序中实现 1-1 私人消息传递功能,如果两个用户同时在聊天屏幕上,则可以实时交换消息,否则消息将存储在我的 postgres 数据库中,并且当用户再次打开聊天时,它们会被加载.

i am trying to implement a 1-1 private messaging feature inside my app, where 2 users can exchange messages live if they are both on the chat screen at the same time and if not the messages get stored in my postgres database and when the user opens the chat again they are loaded.

目前使用我的代码,当两个用户聊天都打开时,当我尝试发送消息时,消息不会实时发送,我需要刷新应用程序才能更新聊天.我认为我的套接字正在工作,因为我的控制台日志在前端和后端控制台中都得到返回.

Currently with my code, when both users chat are open, when i try sending a message, the message does not get sent live i need to refresh the app in order for the chat to update. I think my socket is working since my console logs are getting returned in both frontend and backend consoles.

我的问题是如何使消息生效并正确更新我的平面列表(即新消息出现在倒排列表的底部)?

my problem is how to make the messages live and update my flatlist correctly(ie. the new messages appear at the bottom of my inverted list)?

这是我的代码:

客户端

  const message = route.params.message;
  const [messages, setMessages] = useState([]);
  const [text, setText] = useState('');
  const [socket, setSocket] = useState(null);
  const { user } = useAuth();

  useEffect(() => {
  const newsocket =io.connect(socketURL)
  setMessages(message.Messages)
  newsocket.on('connect', msg => {
  console.log(`user: ${user.id} has joined conversation ${message.id}`)
  setSocket(newsocket)
  });

  newsocket.on("send_message", (msg) => {
  console.log("this is the chat message:", msg);
  const data = [...messages]; 
  data.push(msg);
  setMessages(data); 
  });

  return(()=>newsocket.close());
  }, []);

  const onSend = (ConversationId,senderId,receiverId,message) => {
messagesApi.sendMessage({ConversationId,senderId,receiverId,message});
setText("")
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 });
  };

 const updateText=(text)=>{
 setText(text);
 }

<FlatList
    inverted
    data={messages}
    keyExtractor={(item,index)=>index.toString()}
    extraData={messages}
    renderItem={({item,index})=>(
        <>
        <Text>
         {moment(item.createdAt).fromNow()}
         </Text>
        <MessageBubble
        text={item.message}
        mine={item.senderId !== user.id}
        />
         </>
    )}   
    bounces={false}  
    />
    <View style={styles.messageBoxContainer}>
        <TextInput 
        onChangeText={updateText} 
        value={text} 
        />
        <TouchableOpacity 
         onPress={()=>{
         onSend(
         message.id,
         user.id, 
         (user.id===message.user1?message.user2:message.user1),
         text
         )}}
         >
         <Text>Send</Text>
        </TouchableOpacity>
     </View>

服务端

const express = require("express");
const app = express();
const http = require("http");
const socket = require("socket.io")
const server=http.createServer(app);
const io =socket(server)

io.on('connection', (socket) => {
console.log("connected")
socket.on('message', (data) => {
console.log(data)
socket.emit('send_message', { message: data.message, receiverId: 
data.to,senderId:data.from,conversationId:data.ConversationId })
});
});

在此先感谢您,数周以来我一直在努力解决这个问题,但未能解决.非常感谢您的帮助.

Thank you in advance, i have been trying to solve this problem for weeks and couldnt. Would really appreciate any help.

推荐答案

经过多次尝试,我设法让它工作,这要感谢 Srikanth 对此的回答 使用 node.js 和 socket.io 在密钥之间创建私人聊天.

after many attempts i managed to get it working thanks to Srikanth's answer on this Creating a private chat between a key using a node.js and socket.io.

客户

useEffect(() => {
const newsocket =io.connect("http://192.168.1.103:9000")
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});
};

服务器

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

我读过很多评论,建议不要在 1-1 私人消息中使用房间,但这是让它发挥作用的唯一可能方法.

I have read many comments that suggested not to use rooms in 1-1 private messaging but this was the only possible way of getting it to work.

这篇关于React Native、NodeJS、Socket.io的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆