屏蔽了调试模式下的日志错误,修改了默认服务地址错误的问题,更为正确的wss服务器地址。

This commit is contained in:
tsui110 2026-01-16 12:25:02 +08:00
parent 5c863de337
commit 108f37e35f
5 changed files with 202 additions and 64 deletions

14
main.js
View File

@ -15,6 +15,20 @@ app.$mount()
import { createSSRApp } from 'vue' import { createSSRApp } from 'vue'
export function createApp() { export function createApp() {
const app = createSSRApp(App) const app = createSSRApp(App)
// #ifdef MP-TOUTIAO
// 抖音小程序:忽略开发工具日志通道的 socket 错误
const originalError = console.error
console.error = function(...args) {
const message = args[0]
if (typeof message === 'string' && message.includes('APIScopeError: socket does not exist')) {
// 忽略这个已知的开发工具错误
return
}
originalError.apply(console, args)
}
// #endif
return { return {
app app
} }

View File

@ -76,6 +76,9 @@
"getPhoneNumber" : { "getPhoneNumber" : {
"desc" : "用于登录和账号绑定" "desc" : "用于登录和账号绑定"
} }
},
"optimization" : {
"subPackages" : true
} }
}, },
"uniStatistics" : { "uniStatistics" : {

View File

@ -508,7 +508,7 @@ export default {
try { try {
const res = await new Promise((resolve, reject) => { const res = await new Promise((resolve, reject) => {
uni.request({ uni.request({
url: 'https://game.1024tool.vip/api/internal/game/minesweeper/config', url: 'https://kdy.1024tool.vip/api/internal/game/minesweeper/config',
header: { 'X-Internal-Key': 'bindbox-internal-secret-2024' }, header: { 'X-Internal-Key': 'bindbox-internal-secret-2024' },
success: (res) => resolve(res), success: (res) => resolve(res),
fail: (err) => reject(err) fail: (err) => reject(err)
@ -555,23 +555,28 @@ export default {
}, },
async initNakama(token, server, key, stableUid = null) { async initNakama(token, server, key, stableUid = null) {
try { try {
const serverUrl = server || 'wss://game.1024tool.vip'; const serverUrl = server || 'wss://kdy.1024tool.vip';
const serverKey = key || 'defaultkey'; const serverKey = key || 'defaultkey';
nakamaManager.initClient(serverUrl, serverKey); nakamaManager.initClient(serverUrl, serverKey);
this.gameToken = token; this.gameToken = token;
// WebSocket
// WebSocket APIScopeError
const session = await nakamaManager.authenticateWithGameToken(token, stableUid); const session = await nakamaManager.authenticateWithGameToken(token, stableUid);
this.myUserId = session.user_id; this.myUserId = session.user_id;
this.isConnected = true;
this.addLog('system', '✅ 已连接到远程节点');
this.setupSocketListeners();
// 线 // isConnected = false WebSocket
this.fetchOnlineCount(); // startMatchmaking()
this.onlineCountInterval = setInterval(() => this.fetchOnlineCount(), 10000); this.addLog('system', '✅ 认证成功,准备就绪');
this.setupSocketListeners();
// RPC // RPC
if (!this.matchId) { if (!this.matchId) {
try { try {
// RPC WebSocket
await nakamaManager.connect();
this.isConnected = true;
const activeMatch = await nakamaManager.rpc('find_my_match', {}); const activeMatch = await nakamaManager.rpc('find_my_match', {});
if (activeMatch && activeMatch.match_id) { if (activeMatch && activeMatch.match_id) {
console.log('[RPC发现] 发现服务器端活跃对局:', activeMatch.match_id); console.log('[RPC发现] 发现服务器端活跃对局:', activeMatch.match_id);
@ -593,6 +598,12 @@ export default {
// ID URL // ID URL
if (this.matchId) { if (this.matchId) {
//
if (!this.isConnected) {
await nakamaManager.connect();
this.isConnected = true;
}
this.addLog('system', this.isSpectator ? '🔭 正在切入观察视角...' : '🚪 正在恢复战局...'); this.addLog('system', this.isSpectator ? '🔭 正在切入观察视角...' : '🚪 正在恢复战局...');
try { try {
await nakamaManager.joinMatch(this.matchId); await nakamaManager.joinMatch(this.matchId);
@ -610,7 +621,12 @@ export default {
} }
} }
} catch (e) { } catch (e) {
this.addLog('system', '❌ 通讯异常: ' + e.message); console.error('[初始化错误]', e);
this.addLog('system', '❌ 初始化失败: ' + e.message);
uni.showToast({
title: '连接失败,请重试',
icon: 'none'
});
} }
}, },
setupSocketListeners() { setupSocketListeners() {
@ -706,12 +722,19 @@ export default {
this._isReconnecting = true; this._isReconnecting = true;
console.log('[重连] 开始重新连接...'); console.log('[重连] 开始重新连接...');
// session
if (!nakamaManager.session || !nakamaManager.session.token) {
console.log('[重连] 重新认证...');
const session = await nakamaManager.authenticateWithGameToken(this.gameToken, this.stableUserId); const session = await nakamaManager.authenticateWithGameToken(this.gameToken, this.stableUserId);
this.myUserId = session.user_id; this.myUserId = session.user_id;
}
// WebSocket
await nakamaManager.connect();
this.isConnected = true; this.isConnected = true;
console.log('[重连] 认证成功'); console.log('[重连] WebSocket 连接成功');
this.addLog('system', `✅ 重连成功`); this.addLog('system', `✅ 重连成功`);
// //
@ -897,6 +920,25 @@ export default {
this.logs = []; this.logs = [];
this.addLog('system', '🚀 发射匹配脉冲...'); this.addLog('system', '🚀 发射匹配脉冲...');
// WebSocket
if (!this.isConnected) {
this.addLog('system', '📡 正在建立连接...');
try {
await nakamaManager.connect();
this.isConnected = true;
this.addLog('system', '✅ 连接成功');
} catch (connErr) {
console.error('[连接失败]', connErr);
this.addLog('system', '❌ 连接失败: ' + connErr.message);
uni.showToast({
title: '连接失败,请重试',
icon: 'none'
});
this.isMatching = false;
return;
}
}
clearInterval(this.matchInterval); clearInterval(this.matchInterval);
this.matchInterval = setInterval(() => this.matchingTimer++, 1000); this.matchInterval = setInterval(() => this.matchingTimer++, 1000);
@ -906,7 +948,25 @@ export default {
console.error('Matchmaking error:', e); console.error('Matchmaking error:', e);
this.isMatching = false; this.isMatching = false;
clearInterval(this.matchInterval); clearInterval(this.matchInterval);
this.addLog('system', '❌ 发射失败');
//
let errorMsg = '❌ 匹配失败';
if (e.message) {
if (e.message.includes('socket') || e.message.includes('APIScope')) {
errorMsg = '❌ 网络连接异常,请重试';
} else if (e.message.includes('timeout')) {
errorMsg = '❌ 连接超时,请检查网络';
} else {
errorMsg = '❌ ' + e.message;
}
}
this.addLog('system', errorMsg);
uni.showToast({
title: errorMsg.replace('❌ ', ''),
icon: 'none',
duration: 3000
});
} }
}, },
cancelMatchmaking() { cancelMatchmaking() {

View File

@ -107,12 +107,18 @@ export default {
this.loading = true; this.loading = true;
try { try {
if (!nakamaManager.isConnected) { if (!nakamaManager.isConnected) {
nakamaManager.initClient(this.nakamaServer || 'wss://game.1024tool.vip', this.nakamaKey || 'defaultkey'); nakamaManager.initClient(this.nakamaServer || 'wss://kdy.1024tool.vip', this.nakamaKey || 'defaultkey');
//
await nakamaManager.authenticateWithGameToken(this.gameToken); await nakamaManager.authenticateWithGameToken(this.gameToken);
} }
await this.loadRooms(); await this.loadRooms();
} catch (e) { } catch (e) {
uni.showToast({ title: '连接通讯中心失败', icon: 'none' }); console.error('[房间列表初始化错误]', e);
uni.showToast({
title: '连接失败: ' + (e.message || '未知错误'),
icon: 'none',
duration: 3000
});
} finally { } finally {
this.loading = false; this.loading = false;
} }
@ -120,12 +126,37 @@ export default {
async loadRooms() { async loadRooms() {
this.isRefreshing = true; this.isRefreshing = true;
try { try {
//
if (!nakamaManager.isConnected) {
await nakamaManager.connect();
}
const res = await nakamaManager.rpc('list_matches', {}); const res = await nakamaManager.rpc('list_matches', {});
this.rooms = res || []; this.rooms = res || [];
// //
this.countdown = 5; this.countdown = 5;
} catch (e) { } catch (e) {
console.error('Failed to load rooms', e); console.error('Failed to load rooms', e);
//
let errorMsg = '加载失败';
if (e.message) {
if (e.message.includes('socket') || e.message.includes('APIScope')) {
errorMsg = '网络连接异常';
} else if (e.message.includes('timeout')) {
errorMsg = '连接超时';
} else {
errorMsg = e.message;
}
}
//
if (!this.refreshInterval || this.loading) {
uni.showToast({
title: errorMsg,
icon: 'none'
});
}
} finally { } finally {
this.isRefreshing = false; this.isRefreshing = false;
this.loading = false; this.loading = false;

View File

@ -114,10 +114,9 @@ class NakamaManager {
}; };
console.log('[Nakama] Authenticated, user_id:', this.session.user_id); console.log('[Nakama] Authenticated, user_id:', this.session.user_id);
// 认证成功后建立 WebSocket 连接 // 抖音小程序需要在用户交互后才能建立 WebSocket 连接
this._connectWebSocket() // 这里不自动连接,由业务层在适当时机调用 connect()
.then(() => resolve(this.session)) resolve(this.session);
.catch(reject);
} else { } else {
reject(new Error('Authentication failed: ' + JSON.stringify(res.data))); reject(new Error('Authentication failed: ' + JSON.stringify(res.data)));
} }
@ -129,6 +128,23 @@ class NakamaManager {
}); });
} }
/**
* 手动建立 WebSocket 连接抖音小程序专用
* 在用户交互如点击按钮后调用
*/
connect() {
if (this.isConnected) {
console.log('[Nakama] Already connected');
return Promise.resolve();
}
if (!this.session || !this.session.token) {
return Promise.reject(new Error('Not authenticated. Call authenticateWithGameToken first.'));
}
return this._connectWebSocket();
}
/** /**
* 建立 WebSocket 连接 * 建立 WebSocket 连接
*/ */
@ -157,12 +173,14 @@ class NakamaManager {
console.log('[Nakama] WebSocket connecting...'); console.log('[Nakama] WebSocket connecting...');
try {
this.socketTask = uni.connectSocket({ this.socketTask = uni.connectSocket({
url: wsUrl, url: wsUrl,
complete: () => { } complete: () => { }
}); });
const connectTimeout = setTimeout(() => { const connectTimeout = setTimeout(() => {
this.isConnecting = false;
reject(new Error('WebSocket connection timeout')); reject(new Error('WebSocket connection timeout'));
}, 15000); }, 15000);
@ -178,6 +196,7 @@ class NakamaManager {
this.socketTask.onClose((res) => { this.socketTask.onClose((res) => {
console.log('[Nakama] WebSocket closed:', res.code, res.reason); console.log('[Nakama] WebSocket closed:', res.code, res.reason);
this.isConnected = false; this.isConnected = false;
this.isConnecting = false;
this._stopHeartbeat(); this._stopHeartbeat();
if (this.listeners.ondisconnect) { if (this.listeners.ondisconnect) {
this.listeners.ondisconnect(res); this.listeners.ondisconnect(res);
@ -192,12 +211,17 @@ class NakamaManager {
if (this.listeners.onerror) { if (this.listeners.onerror) {
this.listeners.onerror(err); this.listeners.onerror(err);
} }
reject(new Error('WebSocket connection failed')); reject(new Error('WebSocket connection failed: ' + JSON.stringify(err)));
}); });
this.socketTask.onMessage((res) => { this.socketTask.onMessage((res) => {
this._handleMessage(res.data); this._handleMessage(res.data);
}); });
} catch (error) {
this.isConnecting = false;
console.error('[Nakama] Failed to create socket:', error);
reject(error);
}
}); });
} }
@ -307,9 +331,15 @@ class NakamaManager {
* 开始匹配 * 开始匹配
*/ */
async findMatch(minCount, maxCount) { async findMatch(minCount, maxCount) {
// 如果未连接,先建立连接
if (!this.isConnected) { if (!this.isConnected) {
console.log('[Nakama] Not connected, reconnecting...'); console.log('[Nakama] Not connected, connecting now...');
await this.authenticateWithGameToken(this.gameToken); try {
await this.connect();
} catch (error) {
console.error('[Nakama] Failed to connect:', error);
throw new Error('无法连接到游戏服务器,请稍后重试');
}
} }
if (!this.gameToken) { if (!this.gameToken) {