diff --git a/shared/api/socket.ts b/shared/api/socket.ts index e69de29b..b3a2a65b 100644 --- a/shared/api/socket.ts +++ b/shared/api/socket.ts @@ -0,0 +1,32 @@ +import { io, Socket } from 'socket.io-client'; +import { config } from '../config'; +import _isNil from 'lodash/isNil'; + +let socket: Socket; + +/** + * 创建Socket连接 + * 如果已经有Socket连接则关闭上一个 + * @param token Token + */ +export function createSocket(token: string) { + if (!_isNil(socket)) { + socket.close(); + } + + return new Promise((resolve, reject) => { + socket = io(config.serverUrl, { + transports: ['websocket'], + auth: { + token, + }, + }); + socket.once('connect', () => { + // 连接成功 + resolve(); + }); + socket.once('error', () => { + reject(); + }); + }); +} diff --git a/shared/index.tsx b/shared/index.tsx index 9f476bf1..9d5a9ada 100644 --- a/shared/index.tsx +++ b/shared/index.tsx @@ -1,5 +1,6 @@ // api export { buildStorage } from './api/buildStorage'; +export { createSocket } from './api/socket'; // components export { FastForm } from './components/FastForm/index'; diff --git a/web/src/hooks/useEnsureSocket.ts b/web/src/hooks/useEnsureSocket.ts new file mode 100644 index 00000000..0833a78c --- /dev/null +++ b/web/src/hooks/useEnsureSocket.ts @@ -0,0 +1,17 @@ +import { createSocket, useAsync } from 'pawchat-shared'; +import { getUserJWT } from '../utils/jwt-helper'; + +/** + * 创建全局Socket + */ +export function useEnsureSocket() { + const { loading, error } = useAsync(async () => { + const token = await getUserJWT(); + if (typeof token === 'string') { + await createSocket(token); + console.log('当前socket连接成功'); // TODO + } + }, []); + + return { loading, error }; +} diff --git a/web/src/routes/Entry/index.tsx b/web/src/routes/Entry/index.tsx index 834807f5..6af63917 100644 --- a/web/src/routes/Entry/index.tsx +++ b/web/src/routes/Entry/index.tsx @@ -9,7 +9,7 @@ import { RegisterView } from './RegisterView'; export const EntryRoute = React.memo(() => { return ( -
+
{ + const { loading } = useEnsureSocket(); + + if (loading) { + return ( +
+ +
+ ); + } + return (