带有react-native的套接字文件结构
大家好,我正在使用socket.io和react native,这是我的第一个应用程序。 我正在寻找一个文件结构或系统设计工作 现在我有了一个文件结构,其中首先是:带有react-native的套接字文件结构,react-native,sockets,socket.io,implementation,system-design,React Native,Sockets,Socket.io,Implementation,System Design,大家好,我正在使用socket.io和react native,这是我的第一个应用程序。 我正在寻找一个文件结构或系统设计工作 现在我有了一个文件结构,其中首先是: -splash screen -login screen -Main screen -Network screen: Here the live location will be emitted and a location event 将收听此页面上的地图到地图 在启动屏幕中,有一个useState来检查用户是否在我的
-splash screen
-login screen
-Main screen
-Network screen: Here the live location will be emitted and a location event
将收听此页面上的地图到地图
在启动屏幕中,有一个useState
来检查用户是否在我的持久存储中。如果是,则setUser
并加载主屏幕,如果不是,则useState(null)
并加载登录名
现在我的应用程序必须使用socket.io进行实时位置跟踪等。我想举一个Uber
的例子
我不知道该怎么做。如果我像对待用户一样使用setState
设置套接字连接,那么我指的是如何安排事件、文件和连接。现在,我已经制作了一个名为socket的文件夹,这些是内容
-context: Here I have created a context where I am giving socket, setSocket to all the children screens because I think that's the best way but I it's not working.
-storage: Here I have saved the socket object into the persistent storage for future use(I don't know if this step is correct)
-connection: Here I have specified the connections like socket.on('connect') and other stuff
-useSocket: This is my custom socket hook which I can call and get the socket and stuff
现在的问题是:
import * as SecureStore from 'expo-secure-store';
const key = 'socket';
const storeSocket = async socket => {
try{
await SecureStore.setItemAsync(key, socket);
} catch(error) {
console.log('Error storing the socket',error);
}
}
const getSocket = async () => {
try{
return await SecureStore.getItemAsync(key);
} catch(error) {
console.log('Error getting the socket',error);
}
}
const removeSocket = async() => {
try{
await SecureStore.deleteItemAsync(key);
} catch(error) {
console.log('Error removing the socket', error);
}
}
export default {
getSocket,
storeSocket,
removeSocket,
};
import React from 'react';
const SocketContext = React.createContext();
export default SocketContext;
import { useContext } from 'react';
import SocketStorage from './storage';
import SocketContext from './context';
import { io } from "socket.io-client";
import { socket_host } from '../config/network';
import AuthStorage from '../auth/storage';
export default useAuth = () => {
const {socket, setSocket} = useContext(SocketContext);
const connectSocket = async () => {
if(socket == null) {
const token = await AuthStorage.getToken();
let newSocket = io(socket_host, {auth: {token: token}});
await SocketStorage.storeSocket(newSocket);
setSocket(socket);
} else if(!socket.connected) {
socket.socket.connect();
} else {
//socket is already connected and working. Do nothing.
}
};
const logout = async () => {
setSocket(null);
await SocketStorage.removeSocket();
};
return { socket, setSocket, connectSocket, logout };
}
module.exports = (socket) => {
socket.on('connect', () => {
console.log("Socket Connected");
});
socket.on('disconnect', () => {
});
};