Skip to content

Commit 41c0f76

Browse files
author
Raul Hidalgo Caballero
committed
Closing
1 parent d379d85 commit 41c0f76

File tree

1 file changed

+26
-3
lines changed

1 file changed

+26
-3
lines changed

src/GraphQL.Client/Http/GraphQLHttpSubscriptionResult.cs

Lines changed: 26 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -30,7 +30,7 @@ internal GraphQLHttpSubscriptionResult(Uri webSocketUri, GraphQLRequest graphQLR
3030
this.clientWebSocket.Options.AddSubProtocol("graphql-ws");
3131
}
3232

33-
public async void StartAsync(CancellationToken cancellationToken = default) {
33+
public async Task StartAsync(CancellationToken cancellationToken = default) {
3434
await this.clientWebSocket.ConnectAsync(this.webSocketUri, cancellationToken).ConfigureAwait(false);
3535
if (this.clientWebSocket.State == WebSocketState.Open) {
3636
var arraySegment = new ArraySegment<byte>(this.buffer);
@@ -47,15 +47,38 @@ public async void StartAsync(CancellationToken cancellationToken = default) {
4747
}
4848
}
4949

50-
public void Dispose() => this.clientWebSocket.Dispose();
50+
public async Task StopAsync(CancellationToken cancellationToken = default) {
51+
if (this.clientWebSocket.State == WebSocketState.Open) {
52+
await this.SendCloseMessageAsync();
53+
}
54+
await this.clientWebSocket.CloseAsync(WebSocketCloseStatus.NormalClosure, "", cancellationToken);
55+
}
56+
57+
public void Dispose() {
58+
this.StopAsync().Wait();
59+
this.clientWebSocket.Dispose();
60+
}
5161

5262
private Task SendInitialMessageAsync(CancellationToken cancellationToken = default) {
5363
var webSocketRequest = new GraphQLSubscriptionRequest {
5464
Id = "1",
5565
Type = GQLWebSocketMessageType.GQL_START,
5666
Payload = this.graphQLRequest
5767
};
58-
var webSocketRequestString = JsonConvert.SerializeObject(webSocketRequest);
68+
return this.SendGraphQLSubscriptionRequest(webSocketRequest);
69+
}
70+
71+
private Task SendCloseMessageAsync(CancellationToken cancellationToken = default) {
72+
var webSocketRequest = new GraphQLSubscriptionRequest {
73+
Id = "1",
74+
Type = GQLWebSocketMessageType.GQL_STOP,
75+
Payload = this.graphQLRequest
76+
};
77+
return this.SendGraphQLSubscriptionRequest(webSocketRequest);
78+
}
79+
80+
private Task SendGraphQLSubscriptionRequest(GraphQLSubscriptionRequest graphQLSubscriptionRequest,CancellationToken cancellationToken = default) {
81+
var webSocketRequestString = JsonConvert.SerializeObject(graphQLSubscriptionRequest);
5982
var arraySegmentWebSocketRequest = new ArraySegment<byte>(Encoding.UTF8.GetBytes(webSocketRequestString));
6083
return this.clientWebSocket.SendAsync(arraySegmentWebSocketRequest, WebSocketMessageType.Text, true, cancellationToken);
6184
}

0 commit comments

Comments
 (0)