This commit is contained in:
2026-01-30 11:20:02 +08:00
parent 099880ab72
commit 11cce27665
2 changed files with 42 additions and 122 deletions

160
App.tsx
View File

@@ -102,7 +102,7 @@ class Api {
public static readonly BASE_URL = 'http://192.168.1.155:16000'; public static readonly BASE_URL = 'http://192.168.1.155:16000';
private static _instance: Api | null = null; private static _instance: Api | null = null;
private ws: WebSocket | null = null; private ws: WebSocket | null = null;
private messageCallbacks = new Map<string, (data: any) => void>(); private clientId: string = '';
private constructor() { private constructor() {
} }
@@ -114,157 +114,80 @@ class Api {
return Api._instance; return Api._instance;
} }
public setWebSocket(ws: WebSocket, serverUrl: string) { public setWebSocket(ws: WebSocket, clientId: string) {
this.ws = ws; this.ws = ws;
this.clientId = clientId;
// 处理消息
ws.onmessage = (event) => { ws.onmessage = (event) => {
try { try {
const msg = JSON.parse(event.data); const msg = JSON.parse(event.data);
// 处理响应消息
if (msg.type === 'response' && msg.messageId) {
const callback = this.messageCallbacks.get(msg.messageId);
if (callback) {
callback(msg.data);
this.messageCallbacks.delete(msg.messageId);
}
}
// 处理代理请求
if (msg.type === 'proxyRequest') { if (msg.type === 'proxyRequest') {
console.log('[代理] 收到代理请求:', msg.data);
const { host, port } = msg.data; const { host, port } = msg.data;
// 创建TCP连接
TcpProxy.createProxy( TcpProxy.createProxy(
msg.messageId, msg.messageId,
host, host,
port, port,
// onData: TCP收到数据 → 发送到服务器
(data: string) => { (data: string) => {
ws.send(JSON.stringify({ ws.send(JSON.stringify({ type: 'proxyData', messageId: msg.messageId, data: { data } }));
type: 'proxyData',
messageId: msg.messageId,
data: { data }
}));
}, },
// onClose: TCP关闭 → 通知服务器 () => { ws.send(JSON.stringify({ type: 'proxyClose', messageId: msg.messageId })); },
() => { () => { ws.send(JSON.stringify({ type: 'proxyClose', messageId: msg.messageId })); }
ws.send(JSON.stringify({
type: 'proxyClose',
messageId: msg.messageId
}));
},
// onError: TCP错误 → 通知服务器
(error: string) => {
ws.send(JSON.stringify({
type: 'proxyClose',
messageId: msg.messageId
}));
}
).then(success => { ).then(success => {
if (success) { if (success) ws.send(JSON.stringify({ type: 'proxyReady', messageId: msg.messageId }));
ws.send(JSON.stringify({ }).catch(() => {
type: 'proxyReady', ws.send(JSON.stringify({ type: 'proxyClose', messageId: msg.messageId }));
messageId: msg.messageId
}));
}
}).catch(err => {
ws.send(JSON.stringify({
type: 'proxyClose',
messageId: msg.messageId
}));
}); });
} }
// 处理代理数据(服务器 → TCP
if (msg.type === 'proxyData' && msg.data?.data) { if (msg.type === 'proxyData' && msg.data?.data) {
if (TcpProxy && typeof TcpProxy.writeProxy === 'function') { TcpProxy.writeProxy(msg.messageId, msg.data.data).catch(() => {
TcpProxy.writeProxy(msg.messageId, msg.data.data).then(success => { ws.send(JSON.stringify({ type: 'proxyClose', messageId: msg.messageId }));
if (!success) {
ws.send(JSON.stringify({
type: 'proxyClose',
messageId: msg.messageId
}));
}
}).catch(err => {
ws.send(JSON.stringify({
type: 'proxyClose',
messageId: msg.messageId
}));
}); });
} }
}
// 处理代理关闭
if (msg.type === 'proxyClose') { if (msg.type === 'proxyClose') {
TcpProxy.closeProxy(msg.messageId) TcpProxy.closeProxy(msg.messageId).catch(() => {});
.catch(err => console.error('[代理] 关闭失败:', err));
} }
} catch (error) { } catch (e) {
console.error('[API] 解析消息失败:', error, event.data); console.error('[API]', e, event.data);
} }
}; };
} }
private sendMessage(type: string, data: any): Promise<any> { private headers(): Record<string, string> {
return new Promise((resolve, reject) => { const h: Record<string, string> = { 'Content-Type': 'application/json' };
if (!this.ws || this.ws.readyState !== WebSocket.OPEN) { if (this.clientId) h['X-Client-ID'] = this.clientId;
reject(new Error('WebSocket未连接')); return h;
return;
}
const messageId = `msg_${Date.now()}_${Math.random()}`;
// 设置回调
this.messageCallbacks.set(messageId, (responseData) => {
if (responseData.success) {
resolve(responseData);
} else {
reject(new Error(responseData.message));
}
});
// 发送消息
this.ws.send(JSON.stringify({
type,
messageId,
data
}));
// 超时处理
setTimeout(() => {
if (this.messageCallbacks.has(messageId)) {
this.messageCallbacks.delete(messageId);
reject(new Error('请求超时'));
}
}, 30000);
});
} }
public async register(walletType: WalletType, params: any) { public async register(walletType: WalletType, params: any) {
return this.sendMessage('registerWallet', { const res = await fetch(`${Api.BASE_URL}/register`, {
walletType, method: 'POST',
params headers: this.headers(),
body: JSON.stringify({ walletType, params }),
}); });
const data = await res.json();
if (!data.success) throw new Error(data.message);
return data;
} }
public async requestOTP(walletType: WalletType, mobile: string, params: any = {}) { public async requestOTP(walletType: WalletType, mobile: string, params: any = {}) {
return this.sendMessage('requestOTP', { const res = await fetch(`${Api.BASE_URL}/request-otp`, {
walletType, method: 'POST',
mobile, headers: this.headers(),
...params body: JSON.stringify({ walletType, mobile, ...params }),
}); });
const data = await res.json();
if (!data.success) throw new Error(data.message);
return data;
} }
public async verifyOTP(walletType: WalletType, mobile: string, otp: string, params: any = {}) { public async verifyOTP(walletType: WalletType, mobile: string, otp: string, params: any = {}) {
return this.sendMessage('verifyOTP', { const res = await fetch(`${Api.BASE_URL}/verify-otp`, {
walletType, method: 'POST',
mobile, headers: this.headers(),
otp, body: JSON.stringify({ walletType, mobile, otp, ...params }),
...params
}); });
const data = await res.json();
if (!data.success) throw new Error(data.message);
return data;
} }
} }
@@ -364,15 +287,12 @@ export default class App extends Component<AppProps, AppState> {
ws.onopen = () => { ws.onopen = () => {
console.log('[WebSocket] ✅ 已连接'); console.log('[WebSocket] ✅ 已连接');
// 注册客户端
ws.send(JSON.stringify({ ws.send(JSON.stringify({
type: 'register', type: 'register',
clientId: this.clientId, clientId: this.clientId,
messageId: 'register_' + Date.now() messageId: 'register_' + Date.now()
})); }));
Api.instance.setWebSocket(ws, this.clientId);
// 设置给API使用传入serverUrl用于代理
Api.instance.setWebSocket(ws, serverUrl);
// 启动心跳 // 启动心跳
this.startHeartbeat(ws); this.startHeartbeat(ws);