Nuget 无法与 AppSync 订阅一起开箱即用,因此您需要为此编写自己的客户端代码,就像您在第二个(非 nuget)示例中尝试的那样。
现在,对于第二个示例,请再看一下蟒蛇的例子 https://aws.amazon.com/blogs/mobile/appsync-websockets-python/你的问题中提到。有几个步骤未包含在您的代码中。我将枚举所需的步骤,并尝试将它们从 python 代码移植到 C#(请注意,我手头没有 C# 环境,因此可能存在语法错误,但此代码应该非常接近您需要的内容)
步骤 0 - AppSync 端点
假设调用的结果aws appsync get-graphql-api --api-id example123456
你的 API 是:
{
"graphqlApi": {
"name": "myNewRealTimeGraphQL-API",
"authenticationType": "<API_KEY>",
"tags": {},
"apiId": "example123456",
"uris": {
"GRAPHQL": "https://abc.appsync-api.us-west-2.amazonaws.com/graphql",
"REALTIME": "wss://abc.appsync-realtime-api.us-west-2.amazonaws.com/graphql"
},
"arn": "arn:aws:appsync:us-west-2: xxxxxxxxxxxx:apis/xxxxxxxxxxxx"
}
}
第 1 步 - 构建连接 URL
第 2 步 - 连接到 WebSocket 端点
这包括按照 python 文章中提到的协议发送 connection_init 消息
第 3 步 - 根据协议等待 connection_ack
再次强调,这是按照协议进行的
第 4 步 - 注册订阅
第 5 步 - 发送突变
此步骤不在本响应中,但可以通过 AWS 控制台完成
第 6 步 - 等待“数据”消息
这些是 AppSync 发送的实时事件
第 7 步 - 取消注册订阅
第 8 步 - 断开连接
// These are declared at the same level as your _client
// This comes from the graphqlApi.uris.GRAPHQL in step 0, set as a var here for clarity
_gqlHost = "abc.appsync-api.us-west-2.amazonaws.com";
// This comes from the graphqlApi.uris.REALTIME in step 0, set as a var here for clarity
_realtimeUri = "wss://abc.appsync-realtime-api.us-west-2.amazonaws.com/graphql";
_apiKey = "<API KEY>";
static public async Task CallWebsocket()
{
// Step 1
// This is JSON needed by the server, it will be converted to base64
// (note: might be better to use something like Json.NET for this task)
var header = var test = $@"{{
""host"":""{_gqlHost}"",
""x-api-key"": ""{_apiKey}""
}}";
// Now we need to encode the previous JSON to base64
var headerB64 = System.Convert.ToBase64String(
System.Text.Encoding.UTF8.GetBytes(header));
UriBuilder connectionUriBuilder = new UriBuilder(_realtimeUri);
connectionUriBuilder.Query = $"header={headerB64}&payload=e30=";
try
{
_client = new ClientWebSocket();
_client.Options.AddSubProtocol("graphql-ws");
// Step 2
await _client.ConnectAsync(connectionUriBuilder.Uri), CancellationToken.None);
// Step 3
await SendConnectionInit();
await Receive();
}
catch(Exception ex)
{
}
}
static private async Task SendConnectionInit()
{
ArraySegment<byte> outputBuffer = new ArraySegment<byte>(Encoding.UTF8.GetBytes(@"{""type"": ""connection_init""}"));
await _client.SendAsync(outputBuffer, WebSocketMessageType.Text, true, CancellationToken.None);
}
static private async Task SendSubscription()
{
// This detail is important, note that the subscription is a stringified JSON that will be embeded in the "data" field below
var subscription = $@"{{\""query\"": \""subscription SubscribeToEventComments{{ subscribeToEventComments{{ content }} }}\"", \""variables\"": {{}} }}";
var register = $@"{{
""id"": ""<SUB_ID>"",
""payload"": {{
""data"": ""{subscription}"",
""extensions"": {{
""authorization"": {{
""host"": ""{_gqlHost}"",
""x-api-key"":""{_apiKey}""
}}
}}
}},
""type"": ""start""
}}";
// The output should look like below, note again the "data" field contains a stringified JSON that represents the subscription
/*
{
"id": "<SUB_ID>",
"payload": {
"data": "{\"query\": \"subscription SubscribeToEventComments{ subscribeToEventComments{ content}}\", \"variables\": {} }",
"extensions": {
"authorization": {
"host": "abc.appsync-api.us-west-2.amazonaws.com",
"x-api-key":"<API KEY>"
}
}
},
"type": "start"
}
*/
ArraySegment<byte> outputBuffer = new ArraySegment<byte>(Encoding.UTF8.GetBytes(register));
await _client.SendAsync(outputBuffer, WebSocketMessageType.Text, true, CancellationToken.None);
}
static private async Task Deregister()
{
var deregister = $@"{{
""type"": ""stop"",
""id"": ""<SUB_ID>""
}}"
ArraySegment<byte> outputBuffer = new ArraySegment<byte>(Encoding.UTF8.GetBytes(deregister));
await _client.SendAsync(outputBuffer, WebSocketMessageType.Text, true, CancellationToken.None);
}
static private async Task Receive()
{
while (_socket.State == WebSocketState.Open)
{
ArraySegment<Byte> buffer = new ArraySegment<byte>(new Byte[8192]);
WebSocketReceiveResult result= null;
using (var ms = new MemoryStream())
{
// This loop is needed because the server might send chunks of data that need to be assembled by the client
// see: https://stackoverflow.com/questions/23773407/a-websockets-receiveasync-method-does-not-await-the-entire-message
do
{
result = await socket.ReceiveAsync(buffer, CancellationToken.None);
ms.Write(buffer.Array, buffer.Offset, result.Count);
}
while (!result.EndOfMessage);
ms.Seek(0, SeekOrigin.Begin);
using (var reader = new StreamReader(ms, Encoding.UTF8))
{
// convert stream to string
var message = reader.ReadToEnd();
Console.WriteLine(message)
// quick and dirty way to check response
if (message.Contains("connection_ack"))
{
// Step 4
await SendSubscription();
} else if (message.Contains("data")) // Step 6
{
// Step 7
await Deregister();
// Step 8
await _client.CloseOutputAsync(WebSocketCloseStatus.NormalClosure, string.Empty, CancellationToken.None);
}
}
}
}
}