You can not select more than 25 topics
Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
285 lines
8.4 KiB
285 lines
8.4 KiB
|
3 months ago
|
const WebSocket = require('ws');
|
||
|
|
const readline = require('readline');
|
||
|
|
const mysql = require('mysql2/promise');
|
||
|
|
|
||
|
|
// 数据库连接配置
|
||
|
|
const dbConfig = {
|
||
|
|
host: 'localhost',
|
||
|
|
user: 'root',
|
||
|
|
password: '123456',
|
||
|
|
database: 'wechat_app'
|
||
|
|
};
|
||
|
|
|
||
|
|
// 测试配置
|
||
|
|
const TEST_CONFIG = {
|
||
|
|
wsUrl: 'ws://localhost:3003',
|
||
|
|
testUserId: 'test_user_' + Date.now(),
|
||
|
|
testManagerId: '22',
|
||
|
|
testMessage: '这是一条测试消息 ' + Date.now()
|
||
|
|
};
|
||
|
|
|
||
|
|
// 创建命令行交互界面
|
||
|
|
const rl = readline.createInterface({
|
||
|
|
input: process.stdin,
|
||
|
|
output: process.stdout
|
||
|
|
});
|
||
|
|
|
||
|
|
// WebSocket测试客户端
|
||
|
|
class WebSocketTestClient {
|
||
|
|
constructor() {
|
||
|
|
this.ws = null;
|
||
|
|
this.authenticated = false;
|
||
|
|
this.messages = [];
|
||
|
|
this.connectionAttempts = 0;
|
||
|
|
this.maxAttempts = 3;
|
||
|
|
}
|
||
|
|
|
||
|
|
connect(serverUrl = TEST_CONFIG.wsUrl) {
|
||
|
|
console.log(`正在连接到服务器: ${serverUrl}`);
|
||
|
|
this.connectionAttempts++;
|
||
|
|
|
||
|
|
this.ws = new WebSocket(serverUrl);
|
||
|
|
|
||
|
|
this.ws.on('open', () => {
|
||
|
|
console.log('✅ WebSocket连接已建立');
|
||
|
|
this.connectionAttempts = 0; // 重置连接尝试次数
|
||
|
|
this.authenticate();
|
||
|
|
});
|
||
|
|
|
||
|
|
this.ws.on('message', (data) => {
|
||
|
|
try {
|
||
|
|
const message = JSON.parse(data.toString());
|
||
|
|
console.log('📨 收到消息:', JSON.stringify(message, null, 2));
|
||
|
|
this.handleMessage(message);
|
||
|
|
} catch (error) {
|
||
|
|
console.error('❌ 解析消息失败:', error);
|
||
|
|
}
|
||
|
|
});
|
||
|
|
|
||
|
|
this.ws.on('error', (error) => {
|
||
|
|
console.error('❌ WebSocket错误:', error.message);
|
||
|
|
});
|
||
|
|
|
||
|
|
this.ws.on('close', (code, reason) => {
|
||
|
|
console.log(`🔌 WebSocket连接已关闭: ${code} - ${reason}`);
|
||
|
|
this.authenticated = false;
|
||
|
|
|
||
|
|
// 如果不是主动关闭,尝试重连
|
||
|
|
if (this.connectionAttempts < this.maxAttempts) {
|
||
|
|
console.log(`尝试重连 (${this.connectionAttempts}/${this.maxAttempts})...`);
|
||
|
|
setTimeout(() => this.connect(serverUrl), 2000);
|
||
|
|
}
|
||
|
|
});
|
||
|
|
}
|
||
|
|
|
||
|
|
authenticate() {
|
||
|
|
console.log('正在发送认证信息...');
|
||
|
|
const authMessage = {
|
||
|
|
type: 'auth',
|
||
|
|
userId: TEST_CONFIG.testUserId,
|
||
|
|
userType: 'user',
|
||
|
|
timestamp: Date.now()
|
||
|
|
};
|
||
|
|
|
||
|
|
console.log('🔑 发送认证请求:', JSON.stringify(authMessage));
|
||
|
|
this.sendMessage(authMessage);
|
||
|
|
}
|
||
|
|
|
||
|
|
handleMessage(message) {
|
||
|
|
// 存储接收到的消息
|
||
|
|
this.messages.push(message);
|
||
|
|
|
||
|
|
if (message.type === 'auth_success') {
|
||
|
|
console.log('✅ 认证成功!');
|
||
|
|
this.authenticated = true;
|
||
|
|
this.sendTestMessage();
|
||
|
|
} else if (message.type === 'auth_error') {
|
||
|
|
console.error('❌ 认证失败:', message.message);
|
||
|
|
} else if (message.type === 'message_sent') {
|
||
|
|
console.log('✅ 消息发送成功确认:', message.payload);
|
||
|
|
console.log('消息ID:', message.payload.messageId);
|
||
|
|
console.log('会话ID:', message.payload.conversationId);
|
||
|
|
} else if (message.type === 'new_message') {
|
||
|
|
console.log('📥 收到新消息:', message.payload);
|
||
|
|
this.messages.push(message.payload);
|
||
|
|
} else if (message.type === 'error') {
|
||
|
|
console.error('❌ 收到错误消息:', message.message);
|
||
|
|
}
|
||
|
|
}
|
||
|
|
|
||
|
|
// 数据库查询函数
|
||
|
|
async queryDatabase() {
|
||
|
|
let connection = null;
|
||
|
|
try {
|
||
|
|
console.log('\n🔍 查询数据库验证消息存储...');
|
||
|
|
connection = await mysql.createConnection(dbConfig);
|
||
|
|
|
||
|
|
// 查询最新消息
|
||
|
|
const [messages] = await connection.execute(
|
||
|
|
`SELECT * FROM chat_messages
|
||
|
|
ORDER BY created_at DESC
|
||
|
|
LIMIT 5`
|
||
|
|
);
|
||
|
|
|
||
|
|
if (messages.length > 0) {
|
||
|
|
console.log(`\n📊 找到 ${messages.length} 条最新消息:`);
|
||
|
|
let testMessageFound = false;
|
||
|
|
|
||
|
|
messages.forEach((msg, index) => {
|
||
|
|
console.log(`\n--- 消息 ${index + 1} ---`);
|
||
|
|
console.log(`消息ID: ${msg.message_id}`);
|
||
|
|
console.log(`会话ID: ${msg.conversation_id}`);
|
||
|
|
console.log(`发送者ID: ${msg.sender_id}`);
|
||
|
|
console.log(`内容: ${msg.content}`);
|
||
|
|
|
||
|
|
if (msg.content === TEST_CONFIG.testMessage) {
|
||
|
|
console.log('✅ 测试消息已成功存储到数据库!');
|
||
|
|
testMessageFound = true;
|
||
|
|
}
|
||
|
|
});
|
||
|
|
|
||
|
|
if (!testMessageFound) {
|
||
|
|
console.log('\n⚠️ 未找到测试消息');
|
||
|
|
}
|
||
|
|
} else {
|
||
|
|
console.log('\n❌ 未找到任何消息记录');
|
||
|
|
}
|
||
|
|
|
||
|
|
// 查询最新会话
|
||
|
|
const [conversations] = await connection.execute(
|
||
|
|
`SELECT * FROM chat_conversations
|
||
|
|
ORDER BY created_at DESC
|
||
|
|
LIMIT 5`
|
||
|
|
);
|
||
|
|
|
||
|
|
if (conversations.length > 0) {
|
||
|
|
console.log(`\n📋 找到 ${conversations.length} 条最新会话:`);
|
||
|
|
conversations.forEach((conv, index) => {
|
||
|
|
console.log(`\n--- 会话 ${index + 1} ---`);
|
||
|
|
console.log(`会话ID: ${conv.conversation_id}`);
|
||
|
|
console.log(`用户ID: ${conv.userId}`);
|
||
|
|
console.log(`客服ID: ${conv.managerId}`);
|
||
|
|
});
|
||
|
|
}
|
||
|
|
|
||
|
|
} catch (error) {
|
||
|
|
console.error('\n❌ 数据库查询失败:', error.message);
|
||
|
|
} finally {
|
||
|
|
if (connection) {
|
||
|
|
await connection.end();
|
||
|
|
}
|
||
|
|
}
|
||
|
|
}
|
||
|
|
|
||
|
|
sendTestMessage() {
|
||
|
|
// 生成临时会话ID(前端格式: temp_[currentUserId]_[targetId]_[timestamp])
|
||
|
|
const timestamp = Date.now();
|
||
|
|
const tempConversationId = `temp_${TEST_CONFIG.testUserId}_${TEST_CONFIG.testManagerId}_${timestamp}`;
|
||
|
|
|
||
|
|
console.log(`📝 生成的临时会话ID: ${tempConversationId}`);
|
||
|
|
|
||
|
|
const testMessage = {
|
||
|
|
type: 'chat_message',
|
||
|
|
conversationId: tempConversationId,
|
||
|
|
receiverId: TEST_CONFIG.testManagerId,
|
||
|
|
senderId: TEST_CONFIG.testUserId,
|
||
|
|
senderType: 1,
|
||
|
|
content: TEST_CONFIG.testMessage,
|
||
|
|
contentType: 1,
|
||
|
|
messageId: 'test_msg_' + Date.now(),
|
||
|
|
timestamp: Date.now()
|
||
|
|
};
|
||
|
|
|
||
|
|
console.log('📤 发送测试消息:', JSON.stringify(testMessage));
|
||
|
|
this.sendMessage(testMessage);
|
||
|
|
|
||
|
|
// 发送后自动查询数据库验证
|
||
|
|
setTimeout(() => {
|
||
|
|
this.queryDatabase().catch(console.error);
|
||
|
|
}, 2000);
|
||
|
|
}
|
||
|
|
|
||
|
|
testDatabaseStorage() {
|
||
|
|
console.log('\n=======================================');
|
||
|
|
console.log('📊 测试数据库存储功能');
|
||
|
|
console.log('将自动查询数据库验证消息存储');
|
||
|
|
console.log('=======================================\n');
|
||
|
|
|
||
|
|
// 自动查询数据库
|
||
|
|
this.queryDatabase().catch(console.error);
|
||
|
|
|
||
|
|
// 询问用户是否要发送更多消息
|
||
|
|
this.promptForMoreMessages();
|
||
|
|
}
|
||
|
|
|
||
|
|
promptForMoreMessages() {
|
||
|
|
rl.question('是否发送另一条测试消息?(y/n): ', (answer) => {
|
||
|
|
if (answer.toLowerCase() === 'y') {
|
||
|
|
this.sendTestMessage();
|
||
|
|
} else {
|
||
|
|
console.log('\n测试完成!按Ctrl+C退出。');
|
||
|
|
}
|
||
|
|
});
|
||
|
|
}
|
||
|
|
|
||
|
|
sendMessage(message) {
|
||
|
|
if (this.ws && this.ws.readyState === WebSocket.OPEN) {
|
||
|
|
this.ws.send(JSON.stringify(message));
|
||
|
|
} else {
|
||
|
|
console.error('❌ WebSocket未连接,无法发送消息');
|
||
|
|
}
|
||
|
|
}
|
||
|
|
|
||
|
|
close() {
|
||
|
|
if (this.ws) {
|
||
|
|
this.ws.close();
|
||
|
|
}
|
||
|
|
rl.close();
|
||
|
|
}
|
||
|
|
}
|
||
|
|
|
||
|
|
// 自动测试函数
|
||
|
|
async function autoTest() {
|
||
|
|
console.log('\n========================================');
|
||
|
|
console.log('开始自动测试消息存储功能');
|
||
|
|
console.log('========================================\n');
|
||
|
|
|
||
|
|
const client = new WebSocketTestClient();
|
||
|
|
|
||
|
|
// 重写handleMessage以支持自动测试
|
||
|
|
const originalHandleMessage = client.handleMessage.bind(client);
|
||
|
|
client.handleMessage = function(message) {
|
||
|
|
originalHandleMessage(message);
|
||
|
|
|
||
|
|
if (message.type === 'message_sent') {
|
||
|
|
// 消息发送成功后查询数据库
|
||
|
|
setTimeout(() => {
|
||
|
|
client.queryDatabase().then(() => {
|
||
|
|
console.log('\n========================================');
|
||
|
|
console.log('自动测试完成');
|
||
|
|
console.log('========================================');
|
||
|
|
process.exit(0);
|
||
|
|
});
|
||
|
|
}, 2000);
|
||
|
|
}
|
||
|
|
};
|
||
|
|
|
||
|
|
client.connect();
|
||
|
|
}
|
||
|
|
|
||
|
|
// 启动测试客户端
|
||
|
|
console.log('=======================================');
|
||
|
|
console.log('🚀 消息存储测试工具');
|
||
|
|
console.log('这个工具将测试WebSocket连接、认证和消息存储功能');
|
||
|
|
console.log('=======================================\n');
|
||
|
|
|
||
|
|
// 自动模式运行
|
||
|
|
console.log('🎯 以自动测试模式运行...');
|
||
|
|
autoTest();
|
||
|
|
|
||
|
|
// 处理进程终止
|
||
|
|
process.on('SIGINT', () => {
|
||
|
|
console.log('\n正在关闭连接...');
|
||
|
|
process.exit(0);
|
||
|
|
});
|