-
Notifications
You must be signed in to change notification settings - Fork 986
/
Copy pathAbstractSocketByteChannel.cs
366 lines (323 loc) · 13.4 KB
/
AbstractSocketByteChannel.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
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
// Copyright (c) Microsoft. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.
namespace DotNetty.Transport.Channels.Sockets
{
using System;
using System.Net.Sockets;
using System.Threading;
using DotNetty.Buffers;
using DotNetty.Common.Utilities;
/// <summary>
/// <see cref="AbstractSocketChannel"/> base class for <see cref="IChannel"/>s that operate on bytes.
/// </summary>
public abstract class AbstractSocketByteChannel : AbstractSocketChannel
{
static readonly string ExpectedTypes =
$" (expected: {StringUtil.SimpleClassName<IByteBuffer>()})"; //+ ", " +
// todo: FileRegion support
//typeof(FileRegion).Name + ')';
static readonly Action<object> FlushAction = _ => ((AbstractSocketByteChannel)_).Flush();
static readonly Action<object, object> ReadCompletedSyncCallback = OnReadCompletedSync;
/// <summary>Create a new instance</summary>
/// <param name="parent">the parent <see cref="IChannel"/> by which this instance was created. May be <c>null</c></param>
/// <param name="socket">the underlying <see cref="Socket"/> on which it operates</param>
protected AbstractSocketByteChannel(IChannel parent, Socket socket)
: base(parent, socket)
{
}
protected override IChannelUnsafe NewUnsafe() => new SocketByteChannelUnsafe(this);
protected class SocketByteChannelUnsafe : AbstractSocketUnsafe
{
public SocketByteChannelUnsafe(AbstractSocketByteChannel channel)
: base(channel)
{
}
new AbstractSocketByteChannel Channel => (AbstractSocketByteChannel)this.channel;
void CloseOnRead()
{
this.Channel.ShutdownInput();
if (this.channel.Open)
{
// todo: support half-closure
//if (bool.TrueString.Equals(this.channel.Configuration.getOption(ChannelOption.ALLOW_HALF_CLOSURE))) {
// key.interestOps(key.interestOps() & ~readInterestOp);
// this.channel.Pipeline.FireUserEventTriggered(ChannelInputShutdownEvent.INSTANCE);
//} else {
this.CloseSafe();
//}
}
}
void HandleReadException(IChannelPipeline pipeline, IByteBuffer byteBuf, Exception cause, bool close,
IRecvByteBufAllocatorHandle allocHandle)
{
if (byteBuf != null)
{
if (byteBuf.IsReadable())
{
this.Channel.ReadPending = false;
pipeline.FireChannelRead(byteBuf);
}
else
{
byteBuf.Release();
}
}
allocHandle.ReadComplete();
pipeline.FireChannelReadComplete();
pipeline.FireExceptionCaught(cause);
if (close || cause is SocketException)
{
this.CloseOnRead();
}
}
public override void FinishRead(SocketChannelAsyncOperation operation)
{
AbstractSocketByteChannel ch = this.Channel;
if ((ch.ResetState(StateFlags.ReadScheduled) & StateFlags.Active) == 0)
{
return; // read was signaled as a result of channel closure
}
IChannelConfiguration config = ch.Configuration;
IChannelPipeline pipeline = ch.Pipeline;
IByteBufferAllocator allocator = config.Allocator;
IRecvByteBufAllocatorHandle allocHandle = this.RecvBufAllocHandle;
allocHandle.Reset(config);
IByteBuffer byteBuf = null;
bool close = false;
try
{
operation.Validate();
do
{
byteBuf = allocHandle.Allocate(allocator);
allocHandle.AttemptedBytesRead = byteBuf.WritableBytes;
allocHandle.LastBytesRead = ch.DoReadBytes(byteBuf);
if (allocHandle.LastBytesRead <= 0)
{
// nothing was read -> release the buffer.
byteBuf.Release();
byteBuf = null;
close = allocHandle.LastBytesRead < 0;
break;
}
allocHandle.IncMessagesRead(1);
this.Channel.ReadPending = false;
pipeline.FireChannelRead(byteBuf);
byteBuf = null;
}
while (allocHandle.ContinueReading());
allocHandle.ReadComplete();
pipeline.FireChannelReadComplete();
if (close)
{
this.CloseOnRead();
}
}
catch (Exception t)
{
this.HandleReadException(pipeline, byteBuf, t, close, allocHandle);
}
finally
{
// Check if there is a readPending which was not processed yet.
// This could be for two reasons:
// /// The user called Channel.read() or ChannelHandlerContext.read() input channelRead(...) method
// /// The user called Channel.read() or ChannelHandlerContext.read() input channelReadComplete(...) method
//
// See https://github.com/netty/netty/issues/2254
if (!close && (ch.ReadPending || config.AutoRead))
{
ch.DoBeginRead();
}
}
}
}
protected override void ScheduleSocketRead()
{
SocketChannelAsyncOperation operation = this.ReadOperation;
bool pending;
#if NETSTANDARD1_3
pending = this.Socket.ReceiveAsync(operation);
#else
if (ExecutionContext.IsFlowSuppressed())
{
pending = this.Socket.ReceiveAsync(operation);
}
else
{
using (ExecutionContext.SuppressFlow())
{
pending = this.Socket.ReceiveAsync(operation);
}
}
#endif
if (!pending)
{
// todo: potential allocation / non-static field?
this.EventLoop.Execute(ReadCompletedSyncCallback, this.Unsafe, operation);
}
}
static void OnReadCompletedSync(object u, object e) => ((ISocketChannelUnsafe)u).FinishRead((SocketChannelAsyncOperation)e);
protected override void DoWrite(ChannelOutboundBuffer input)
{
int writeSpinCount = -1;
while (true)
{
object msg = input.Current;
if (msg == null)
{
// Wrote all messages.
break;
}
if (msg is IByteBuffer)
{
var buf = (IByteBuffer)msg;
int readableBytes = buf.ReadableBytes;
if (readableBytes == 0)
{
input.Remove();
continue;
}
bool scheduleAsync = false;
bool done = false;
long flushedAmount = 0;
if (writeSpinCount == -1)
{
writeSpinCount = this.Configuration.WriteSpinCount;
}
for (int i = writeSpinCount - 1; i >= 0; i--)
{
int localFlushedAmount = this.DoWriteBytes(buf);
if (localFlushedAmount == 0) // todo: check for "sent less than attempted bytes" to avoid unnecessary extra doWriteBytes call?
{
scheduleAsync = true;
break;
}
flushedAmount += localFlushedAmount;
if (!buf.IsReadable())
{
done = true;
break;
}
}
input.Progress(flushedAmount);
if (done)
{
input.Remove();
}
else if (this.IncompleteWrite(scheduleAsync, this.PrepareWriteOperation(buf.GetIoBuffer())))
{
break;
}
} /*else if (msg is FileRegion) { todo: FileRegion support
FileRegion region = (FileRegion) msg;
bool done = region.transfered() >= region.count();
bool scheduleAsync = false;
if (!done) {
long flushedAmount = 0;
if (writeSpinCount == -1) {
writeSpinCount = config().getWriteSpinCount();
}
for (int i = writeSpinCount - 1; i >= 0; i--) {
long localFlushedAmount = doWriteFileRegion(region);
if (localFlushedAmount == 0) {
scheduleAsync = true;
break;
}
flushedAmount += localFlushedAmount;
if (region.transfered() >= region.count()) {
done = true;
break;
}
}
input.progress(flushedAmount);
}
if (done) {
input.remove();
} else {
incompleteWrite(scheduleAsync);
break;
}
}*/
else
{
// Should not reach here.
throw new InvalidOperationException();
}
}
}
protected override object FilterOutboundMessage(object msg)
{
if (msg is IByteBuffer)
{
return msg;
//IByteBuffer buf = (IByteBuffer) msg;
//if (buf.isDirect()) {
// return msg;
//}
//return newDirectBuffer(buf);
}
// todo: FileRegion support
//if (msg is FileRegion) {
// return msg;
//}
throw new NotSupportedException(
"unsupported message type: " + msg.GetType().Name + ExpectedTypes);
}
protected bool IncompleteWrite(bool scheduleAsync, SocketChannelAsyncOperation operation)
{
// Did not write completely.
if (scheduleAsync)
{
this.SetState(StateFlags.WriteScheduled);
bool pending;
#if NETSTANDARD1_3
pending = this.Socket.SendAsync(operation);
#else
if (ExecutionContext.IsFlowSuppressed())
{
pending = this.Socket.SendAsync(operation);
}
else
{
using (ExecutionContext.SuppressFlow())
{
pending = this.Socket.SendAsync(operation);
}
}
#endif
if (!pending)
{
((ISocketChannelUnsafe)this.Unsafe).FinishWrite(operation);
}
return pending;
}
else
{
// Schedule flush again later so other tasks can be picked up input the meantime
this.EventLoop.Execute(FlushAction, this);
return true;
}
}
// todo: support FileRegion
///// <summary>
// /// Write a {@link FileRegion}
// *
// /// @param region the {@link FileRegion} from which the bytes should be written
// /// @return amount the amount of written bytes
// /// </summary>
//protected abstract long doWriteFileRegion(FileRegion region);
/// <summary>
/// Reads bytes into the given <see cref="IByteBuffer"/> and returns the number of bytes that were read.
/// </summary>
/// <param name="buf">The <see cref="IByteBuffer"/> to read bytes into.</param>
/// <returns>The number of bytes that were read into the buffer.</returns>
protected abstract int DoReadBytes(IByteBuffer buf);
/// <summary>
/// Writes bytes from the given <see cref="IByteBuffer"/> to the underlying <see cref="IChannel"/>.
/// </summary>
/// <param name="buf">The <see cref="IByteBuffer"/> from which the bytes should be written.</param>
/// <returns>The number of bytes that were written from the buffer.</returns>
protected abstract int DoWriteBytes(IByteBuffer buf);
}
}