我正在尝试为套接字io编写集成测试。当捕获到错误时,我正在使用try-catch来处理服务器事件,我会为客户端发出事件以处理错误
io.of('/rooms').on('connection', socket => {
const socketId = socket.id;
console.log('server socketid', socketId);
const userRepository = getCustomRepository(UserRepository);
const conversationToUserRepository = getCustomRepository(ConversationToUserRepository);
socket.on('initGroupChat', async (users_id, fn) => {
try {
const [user, listConversationToUser] = await Promise.all([
userRepository.findOne({
where: {
users_id,
},
}),
conversationToUserRepository.find({
where: {
users_id,
},
}),
]);
if (!user) {
throw new NotFoundError('User not found with id: ' + users_id);
}
console.log(2);
user.socket_id = socket.id;
await userRepository.save(user);
for (const item of listConversationToUser) {
socket.join(item.conversation_id.toString());
}
fn('init group chat success');
} catch (error) {
io.to(socketId).emit('error', errorHandlerForSocket(error));
console.log(10);
}
});
});
但是在套接字客户端上,什么也没有发生。这是代码套接字客户端:
it.only('Init Group Chat with error', done => {
socket = io.connect(`http://localhost:${env.app.port}/rooms`, {
transports: ['websocket']
});
const id = 11111;
socket.emit('initGroupChat', id, (response: any) => {
console.log('response', response);
});
socket.on('error', (error: any) => {
console.log('error3', error);
done();
});
});
在错误事件上,console.log没有显示在终止上。它没有捕获我在服务器上发出的事件。
谁能帮助我解决此问题
答案 0 :(得分:1)
每次客户端刷新socketId更改。
服务器:
io.emit("send_to_client", {
userId: 112233,
data: "Hello user 112233"
});
客户:
var userLogin = 112233;
socket.on("send_to_client", function(res) {
if(res.userId === userLogin)
//somethingElse
});