Skip to content

Commit 7984635

Browse files
committed
修复问题
1 parent 4eaae9a commit 7984635

File tree

1 file changed

+28
-16
lines changed

1 file changed

+28
-16
lines changed

src/store/useChatStore.ts

Lines changed: 28 additions & 16 deletions
Original file line numberDiff line numberDiff line change
@@ -152,17 +152,21 @@ const useChatStore = create<ChatState>((set, get) => ({
152152
const { peer, userName } = get()
153153
if (!peer || !userName) return
154154

155+
// 使用nanoid生成不带横线的ID,长度为16
156+
const groupId = nanoid(16)
157+
console.log(`创建群聊,使用nanoid生成的ID: ${groupId}`)
158+
155159
// 创建一个新的群聊
156160
const groupChat: GroupChat = {
157-
id: peer.id,
161+
id: peer.id, // 保持id为peer.id,用于标识聊天
158162
name: `${userName}的群聊`,
159163
isGroup: true,
160164
users: [{ id: peer.id, name: userName }],
161165
connections: [],
162166
messages: [],
163-
roomId: peer.id,
167+
roomId: groupId, // 使用nanoid生成的ID作为roomId
164168
isHost: true,
165-
shareLink: `${window.location.origin}${window.location.pathname}?roomId=${peer.id}`
169+
shareLink: `${window.location.origin}${window.location.pathname}?roomId=${groupId}`
166170
}
167171

168172
// 添加系统消息
@@ -320,13 +324,17 @@ const useChatStore = create<ChatState>((set, get) => ({
320324
// 提供更详细的错误信息
321325
let errorMessage = '连接失败'
322326
if (err.type && err.type.toString() === 'peer-unavailable') {
323-
errorMessage = '无法连接到指定的群聊,可能群聊已不存在或暂时不可用'
327+
errorMessage = `无法连接到指定的群聊,可能群聊已不存在或暂时不可用`
328+
console.log(`无法连接到群聊ID: ${cleanedRoomId}`)
329+
330+
// 不再需要检查ID是否被截断,因为我们现在使用nanoid生成不带横线的ID
331+
chatEvents.emit('error', errorMessage)
332+
set({ isConnecting: false })
324333
} else {
325334
errorMessage = `连接错误: ${err.message || '无法连接到群聊'}`
335+
chatEvents.emit('error', errorMessage)
336+
set({ isConnecting: false })
326337
}
327-
328-
chatEvents.emit('error', errorMessage)
329-
set({ isConnecting: false })
330338
})
331339

332340
conn.on('close', () => {
@@ -462,19 +470,23 @@ const useChatStore = create<ChatState>((set, get) => ({
462470

463471
// 清理 roomId
464472
function cleanRoomId(id: string): string {
465-
// 移除可能导致连接问题的字符,如重复的 ID 部分 (hwW6wz-hwW6wz)
466-
if (id.includes('-')) {
467-
const parts = id.split('-')
468-
// 如果破折号两边的部分相同,只返回一部分
473+
// 移除空格
474+
let cleanedId = id.trim()
475+
476+
// 如果是旧版本的带破折号的ID,尝试清理
477+
if (cleanedId.includes('-')) {
478+
// 检查是否是旧版本的PeerJS自动生成的ID
479+
const parts = cleanedId.split('-')
469480
if (parts[0] === parts[1]) {
470-
console.log(`检测到重复ID格式: ${id} -> ${parts[0]}`)
481+
console.log(`检测到重复ID格式: ${cleanedId} -> ${parts[0]}`)
471482
return parts[0]
472483
}
473-
// 如果是其他格式的破折号,可能是 PeerJS 内部使用的格式,尝试使用第一部分
474-
console.log(`检测到带破折号的ID: ${id} -> ${parts[0]}`)
475-
return parts[0]
484+
485+
// 对于其他带破折号的ID,保留完整ID
486+
console.log(`检测到带破折号的ID,保留完整ID: ${cleanedId}`)
476487
}
477-
return id
488+
489+
return cleanedId
478490
}
479491

480492
// 设置 Peer 监听器

0 commit comments

Comments
 (0)