/
LongPollingTransport.cs
269 lines (222 loc) · 7.73 KB
/
LongPollingTransport.cs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
using System;
using System.Collections.Generic;
using System.Threading.Tasks;
using SignalR.Infrastructure;
namespace SignalR.Transports
{
public class LongPollingTransport : TransportDisconnectBase, ITransport
{
private IJsonSerializer _jsonSerializer;
// This should be ok to do since long polling request never hang around too long
// so we won't bloat memory
private const int MaxMessages = 5000;
public LongPollingTransport(HostContext context, IDependencyResolver resolver)
: this(context,
resolver.Resolve<IJsonSerializer>(),
resolver.Resolve<ITransportHeartBeat>())
{
}
public LongPollingTransport(HostContext context, IJsonSerializer jsonSerializer, ITransportHeartBeat heartBeat)
: base(context, jsonSerializer, heartBeat)
{
_jsonSerializer = jsonSerializer;
}
// Static events intended for use when measuring performance
public static event Action<string> Sending;
public static event Action<PersistentResponse> SendingResponse;
public static event Action<string> Receiving;
/// <summary>
/// The number of milliseconds to tell the browser to wait before restablishing a
/// long poll connection after data is sent from the server. Defaults to 0.
/// </summary>
public static long LongPollDelay
{
get;
set;
}
public override TimeSpan DisconnectThreshold
{
get { return TimeSpan.FromMilliseconds(LongPollDelay); }
}
protected override bool IsConnectRequest
{
get
{
return Context.Request.Url.LocalPath.EndsWith("/connect", StringComparison.OrdinalIgnoreCase);
}
}
private bool IsReconnectRequest
{
get
{
return Context.Request.Url.LocalPath.EndsWith("/reconnect", StringComparison.OrdinalIgnoreCase);
}
}
private bool IsJsonp
{
get
{
return !String.IsNullOrEmpty(JsonpCallback);
}
}
private bool IsSendRequest
{
get
{
return Context.Request.Url.LocalPath.EndsWith("/send", StringComparison.OrdinalIgnoreCase);
}
}
private string MessageId
{
get
{
return Context.Request.QueryString["messageId"];
}
}
private string JsonpCallback
{
get
{
return Context.Request.QueryString["callback"];
}
}
public override bool SupportsKeepAlive
{
get
{
return false;
}
}
public Func<string, Task> Received { get; set; }
public Func<Task> TransportConnected { get; set; }
public Func<Task> Connected { get; set; }
public Func<Task> Reconnected { get; set; }
public Task ProcessRequest(ITransportConnection connection)
{
Connection = connection;
if (IsSendRequest)
{
return ProcessSendRequest();
}
else if (IsAbortRequest)
{
return Connection.Abort(ConnectionId);
}
else
{
if (IsConnectRequest)
{
return ProcessConnectRequest(connection);
}
else if (MessageId != null)
{
if (IsReconnectRequest && Reconnected != null)
{
// Return a task that completes when the reconnected event task & the receive loop task are both finished
return TaskAsyncHelper.Interleave(ProcessReceiveRequest, Reconnected, connection, Completed);
}
return ProcessReceiveRequest(connection);
}
}
return null;
}
public virtual Task Send(PersistentResponse response)
{
HeartBeat.MarkConnection(this);
if (SendingResponse != null)
{
SendingResponse(response);
}
AddTransportData(response);
return Send((object)response);
}
public virtual Task Send(object value)
{
Context.Response.ContentType = IsJsonp ? Json.JsonpMimeType : Json.MimeType;
if (IsJsonp)
{
OutputWriter.Write(JsonpCallback);
OutputWriter.Write("(");
}
_jsonSerializer.Stringify(value, OutputWriter);
if (IsJsonp)
{
OutputWriter.Write(");");
}
OutputWriter.Flush();
return Context.Response.EndAsync();
}
private Task ProcessSendRequest()
{
string data = IsJsonp ? Context.Request.QueryString["data"] : Context.Request.Form["data"];
if (Receiving != null)
{
Receiving(data);
}
if (Received != null)
{
return Received(data);
}
return TaskAsyncHelper.Empty;
}
private Task ProcessConnectRequest(ITransportConnection connection)
{
if (Connected != null)
{
bool newConnection = HeartBeat.AddConnection(this);
// Return a task that completes when the connected event task & the receive loop task are both finished
return TaskAsyncHelper.Interleave(ProcessReceiveRequestWithoutTracking, () =>
{
if (newConnection)
{
return Connected();
}
return TaskAsyncHelper.Empty;
},
connection, Completed);
}
return ProcessReceiveRequest(connection);
}
private Task ProcessReceiveRequest(ITransportConnection connection, Action postReceive = null)
{
HeartBeat.AddConnection(this);
return ProcessReceiveRequestWithoutTracking(connection, postReceive);
}
private Task ProcessReceiveRequestWithoutTracking(ITransportConnection connection, Action postReceive = null)
{
if (TransportConnected != null)
{
TransportConnected().Catch();
}
// ReceiveAsync() will async wait until a message arrives then return
var receiveTask = IsConnectRequest ?
connection.ReceiveAsync(null, ConnectionEndToken, MaxMessages) :
connection.ReceiveAsync(MessageId, ConnectionEndToken, MaxMessages);
if (postReceive != null)
{
postReceive();
}
return receiveTask.Then(response =>
{
response.TimedOut = IsTimedOut;
if (response.Aborted)
{
// If this was a clean disconnect then raise the event
OnDisconnect();
}
return Send(response);
});
}
private void AddTransportData(PersistentResponse response)
{
if (LongPollDelay > 0)
{
if (response.TransportData == null)
{
response.TransportData = new Dictionary<string, object>();
}
response.TransportData["LongPollDelay"] = LongPollDelay;
}
}
}
}