我正在尝试连接到由 Pusher 使用 Laravel 后端开发的私有频道,我使用了 Pusher_channels_flutter 包,但问题是该包对如何连接私有频道的解释很差,我已经连接了在使用这个包之前有公共频道,但在它是私有的时候无法连接它,我尝试了 GitHub 提供的不同解决方案,在这里,我最后设置的推送器配置是这样的:
import 'dart:convert';
import 'package:chat_test/services/local_data.dart';
import 'package:pusher_channels_flutter/pusher_channels_flutter.dart';
import 'package:http/http.dart' as http;
class PusherConfig {
PusherChannelsFlutter pusher = PusherChannelsFlutter.getInstance();
pusherget(int id , Function(dynamic e) oncontrollerevent , Function(dynamic e) oneevent) async {
// print(Shared.getstring("token"));
await pusher.init(
apiKey: "2.....7",
cluster: "us2",
onConnectionStateChange: onConnectionStateChange,
onSubscriptionError: onSubscriptionError,
onSubscriptionSucceeded: onSubscriptionSucceeded,
onEvent: oncontrollerevent,
onAuthorizer: onAuthorizer
);
await pusher.subscribe(channelName: 'private-chat.${int.parse(Shared.getstring("id")!)}', onEvent: oneevent);
await pusher.connect();
}
dynamic onAuthorizer(
String channelName, String socketId, dynamic options) async {
String token = Shared.getstring("token")!;
var authUrl = "http://192.168.1.102:8000//broadcasting/auth";
var result = await http.post(
Uri.parse(authUrl),
headers: {
'Content-Type': 'application/x-www-form-urlencoded',
'Authorization': 'Bearer ${token}',
},
body: 'socket_id=$socketId&channel_name=$channelName',
);
var json = jsonDecode(result.body);
return json;
}
void onEvent(PusherEvent event) {
print("onEvent: ${event.data}");
}
void onSubscriptionSucceeded(String channelName, dynamic data) {
print("onSubscriptionSucceeded: $channelName data: $data");
}
void onSubscriptionError(String message, dynamic e) {
print("onSubscriptionError: $message Exception: $e");
}
void onMemberRemoved(String channelName, PusherMember member) {
print("onMemberRemoved: $channelName member: $member");
}
void onConnectionStateChange(
dynamic currentState, dynamic previousState) async {
print("Connection: $currentState");
if (currentState == "CONNECTED") {
var s = await pusher.getSocketId();
print(s);
}
}
// void onPusherEvent(dynamic event) {
// // Handle the received event here
// print("Received event: ${event.data}");
// // Add your event handling logic here
// }
}
OnAuthorizer 是使用 Pusher 进行授权的方法,从 Pusher 返回的错误是这样的: Pusher 授权错误:错误 I/flutter (29115): onSubscriptionError: 没有收到 ChannelAuthorizer 期望的所有字段,期望身份验证和共享秘密。异常:com.pusher.client.AuthorizationFailureException:没有收到 ChannelAuthorizer 期望的所有字段,期望身份验证和共享秘密。
我不明白我应该做什么,或者我应该发送什么身份验证和共享秘密以及如何发送? ,shared_secret是secret_key本身还是不同的
有什么解决方案可以解决这个问题吗?
这是一个令牌问题,也许您需要在此处放置
await
关键字 String token = Shared.getstring("token")!;
来等待令牌获取,我认为您的代码导致返回 null
而不是令牌本身,因为它是未来。