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