向未连接的用户发送消息?

时间:2020-10-10 15:33:26

标签: node.js socket.io

我正在尝试创建一个用户到用户聊天应用程序-无群聊或其他任何内容。 我在后端使用NodeJSSocket.io,在前端使用React Native

我最终有一个Map,它存储一个user id及其对应的socket id,我的问题是,只有当用户连接到服务器时,他才会获得套接字ID。 但是,如果用户A已连接并试图向用户B发送消息,而用户B未连接,因此它没有套接字ID,那我该怎么办呢。

这是我到目前为止得到的:

io.on("connection", (socket: Socket) => {
  //Whenever a user will connect, the user will emit 'initiate' to register itself and it's socket id to the server.
  //We will be using this userSocketMap to send messages between users.
  socket.on(SocketEvents.INITIATE, (data) => {
    const uid = data.uid;
    const socketID = socket.id;

    userSocketMap.set(uid, socketID);
  });

  //This function will get called when a user is sending message to another user.
  socket.on(SocketEvents.SEND, (data) => {
    const to = data.to;
    const from = data.from;
    const content = data.content;

    const payload: MessagePayload = {
      to: to,
      from: from,
      content: content,
    };

    const dstUser = userSocketMap.get(to); // getting the socket id of the receiver.

    // '/#' is the prefix for the socketID, if the socketID already has this prefix, this should be deleted - need to check this.
    //MessageEvent.RECEIVE is used to signal the dstUser to receive a message.
    io.to("/#" + dstUser).emit(SocketEvents.RECEIVE, { payload: payload });
  });

  socket.on(SocketEvents.DISCONNECT, (socket: Socket) => {
    const userID = getByValue(socket.id);
    if (!userID) return;

    userSocketMap.delete(userID);
  });
});

1 个答案:

答案 0 :(得分:0)

在使用react-native和socket.io时,您应该做两件事,以防用户失去互联网连接。使用socket.io心跳机制可以获取失去连接并且没有响应的用户,并使用NetInfo软件包通知移动用户他已经失去了互联网连接。

Socket.io

var server = app.listen(80);
var io = socketio(server,{'pingInterval': 2000});

io.on("connection", (socket: Socket) => {
    socket.on(SocketEvents.INITIATE, (data) => {
        const uid = data.uid;
        const socketID = socket.id;

        userSocketMap.set(uid, socketID);
    })

    socket.on('heartbeat', (socket: Socket) => {
        const userID = getByValue(socket.id)
        userSocketMap.MARK_USER_AS_INACTIVE(userID)
   })

});

React-Native-使用NetInfo-它曾经是核心的一部分,但被隔离到社区模块中

import NetInfo from "@react-native-community/netinfo";

NetInfo.fetch().then(state => {
    console.log("Connection type", state.type);
    console.log("Is connected?", state.isConnected);
});

const unsubscribe = NetInfo.addEventListener(state => {
    console.log("Connection type", state.type);
    console.log("Is connected?", state.isConnected);
});

// Unsubscribe
unsubscribe();