fix: 兼容 Web 同源部署地址

This commit is contained in:
2026-06-24 21:10:21 +08:00
parent 7cb51e70a3
commit 2281c98b1b
2 changed files with 40 additions and 10 deletions

View File

@@ -45,7 +45,7 @@ class ChatService {
Stream<ChatMessage> get messages => _messageController.stream;
void connect(String baseUrl, String roomId, String username) {
final wsUri = Uri.parse(baseUrl).replace(
final wsUri = _webSocketUri(baseUrl).replace(
scheme: 'ws',
path: '/api/ws/room/$roomId',
queryParameters: {'username': username},
@@ -83,6 +83,21 @@ class ChatService {
}
}
Uri _webSocketUri(String baseUrl) {
if (baseUrl.isEmpty) {
if (kIsWeb) {
return Uri.base.replace(
scheme: Uri.base.scheme == 'https' ? 'wss' : 'ws',
);
}
return Uri.parse('http://localhost:8080');
}
final uri = Uri.parse(baseUrl);
final scheme = uri.scheme == 'https' ? 'wss' : 'ws';
return uri.replace(scheme: scheme);
}
void dispose() {
_channel?.sink.close();
_messageController.close();