View Javadoc
1   /*
2    * Copyright 2012 The Netty Project
3    *
4    * The Netty Project licenses this file to you under the Apache License,
5    * version 2.0 (the "License"); you may not use this file except in compliance
6    * with the License. You may obtain a copy of the License at:
7    *
8    *   http://www.apache.org/licenses/LICENSE-2.0
9    *
10   * Unless required by applicable law or agreed to in writing, software
11   * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
12   * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
13   * License for the specific language governing permissions and limitations
14   * under the License.
15   */
16  package io.netty.channel;
17  
18  import io.netty.buffer.ByteBuf;
19  import io.netty.buffer.ByteBufAllocator;
20  import io.netty.channel.socket.DatagramChannel;
21  import io.netty.channel.socket.DatagramPacket;
22  import io.netty.channel.socket.ServerSocketChannel;
23  import io.netty.channel.socket.SocketChannel;
24  import io.netty.util.AttributeMap;
25  import io.netty.util.concurrent.FutureListener;
26  
27  import java.util.concurrent.ScheduledExecutorService;
28  import java.util.concurrent.RejectedExecutionException;
29  import java.net.ConnectException;
30  import java.net.InetSocketAddress;
31  import java.net.SocketAddress;
32  
33  
34  /**
35   * A nexus to a network socket or a component which is capable of I/O
36   * operations such as read, write, connect, and bind.
37   * <p>
38   * A channel provides a user:
39   * <ul>
40   * <li>the current state of the channel (e.g. is it open? is it connected?),</li>
41   * <li>the {@linkplain ChannelConfig configuration parameters} of the channel (e.g. receive buffer size),</li>
42   * <li>the I/O operations that the channel supports (e.g. read, write, connect, and bind), and</li>
43   * <li>the {@link ChannelPipeline} which handles all I/O events and requests
44   *     associated with the channel.</li>
45   * </ul>
46   *
47   * <h3>All I/O operations are asynchronous.</h3>
48   * <p>
49   * All I/O operations in Netty are asynchronous.  It means any I/O calls will
50   * return immediately with no guarantee that the requested I/O operation has
51   * been completed at the end of the call.  Instead, you will be returned with
52   * a {@link ChannelFuture} instance which will notify you when the requested I/O
53   * operation has succeeded, failed, or canceled.
54   *
55   * <h3>Channels are hierarchical</h3>
56   * <p>
57   * A {@link Channel} can have a {@linkplain #parent() parent} depending on
58   * how it was created.  For instance, a {@link SocketChannel}, that was accepted
59   * by {@link ServerSocketChannel}, will return the {@link ServerSocketChannel}
60   * as its parent on {@link #parent()}.
61   * <p>
62   * The semantics of the hierarchical structure depends on the transport
63   * implementation where the {@link Channel} belongs to.  For example, you could
64   * write a new {@link Channel} implementation that creates the sub-channels that
65   * share one socket connection, as <a href="http://beepcore.org/">BEEP</a> and
66   * <a href="http://en.wikipedia.org/wiki/Secure_Shell">SSH</a> do.
67   *
68   * <h3>Downcast to access transport-specific operations</h3>
69   * <p>
70   * Some transports exposes additional operations that is specific to the
71   * transport.  Down-cast the {@link Channel} to sub-type to invoke such
72   * operations.  For example, with the old I/O datagram transport, multicast
73   * join / leave operations are provided by {@link DatagramChannel}.
74   *
75   * <h3>Release resources</h3>
76   * <p>
77   * It is important to call {@link #close()} or {@link #close(ChannelPromise)} to release all
78   * resources once you are done with the {@link Channel}. This ensures all resources are
79   * released in a proper way, i.e. filehandles.
80   */
81  public interface Channel extends AttributeMap, Comparable<Channel> {
82  
83      /**
84       * Returns the globally unique identifier of this {@link Channel}.
85       */
86      ChannelId id();
87  
88      /**
89       * Return the {@link EventLoop} this {@link Channel} was registered too.
90       */
91      EventLoop eventLoop();
92  
93      /**
94       * Returns the parent of this channel.
95       *
96       * @return the parent channel.
97       *         {@code null} if this channel does not have a parent channel.
98       */
99      Channel parent();
100 
101     /**
102      * Returns the configuration of this channel.
103      */
104     ChannelConfig config();
105 
106     /**
107      * Returns {@code true} if the {@link Channel} is open an may get active later
108      */
109     boolean isOpen();
110 
111     /**
112      * Returns {@code true} if the {@link Channel} is registered with an {@link EventLoop}.
113      */
114     boolean isRegistered();
115 
116     /**
117      * Return {@code true} if the {@link Channel} is active and so connected.
118      */
119     boolean isActive();
120 
121     /**
122      * Return the {@link ChannelMetadata} of the {@link Channel} which describe the nature of the {@link Channel}.
123      */
124     ChannelMetadata metadata();
125 
126     /**
127      * Returns the local address where this channel is bound to.  The returned
128      * {@link SocketAddress} is supposed to be down-cast into more concrete
129      * type such as {@link InetSocketAddress} to retrieve the detailed
130      * information.
131      *
132      * @return the local address of this channel.
133      *         {@code null} if this channel is not bound.
134      */
135     SocketAddress localAddress();
136 
137     /**
138      * Returns the remote address where this channel is connected to.  The
139      * returned {@link SocketAddress} is supposed to be down-cast into more
140      * concrete type such as {@link InetSocketAddress} to retrieve the detailed
141      * information.
142      *
143      * @return the remote address of this channel.
144      *         {@code null} if this channel is not connected.
145      *         If this channel is not connected but it can receive messages
146      *         from arbitrary remote addresses (e.g. {@link DatagramChannel},
147      *         use {@link DatagramPacket#recipient()} to determine
148      *         the origination of the received message as this method will
149      *         return {@code null}.
150      */
151     SocketAddress remoteAddress();
152 
153     /**
154      * Returns the {@link ChannelFuture} which will be notified when this
155      * channel is closed.  This method always returns the same future instance.
156      */
157     ChannelFuture closeFuture();
158 
159     /**
160      * Returns {@code true} if and only if the I/O thread will perform the
161      * requested write operation immediately.  Any write requests made when
162      * this method returns {@code false} are queued until the I/O thread is
163      * ready to process the queued write requests.
164      */
165     boolean isWritable();
166 
167     /**
168      * Returns an <em>internal-use-only</em> object that provides unsafe operations.
169      */
170     Unsafe unsafe();
171 
172     /**
173      * Return the assigned {@link ChannelPipeline}
174      */
175     ChannelPipeline pipeline();
176 
177     /**
178      * Return the assigned {@link ByteBufAllocator} which will be used to allocate {@link ByteBuf}s.
179      */
180     ByteBufAllocator alloc();
181 
182     /**
183      * Return a new {@link ChannelPromise}.
184      */
185     ChannelPromise newPromise();
186 
187     /**
188      * Return an new {@link ChannelProgressivePromise}
189      */
190     ChannelProgressivePromise newProgressivePromise();
191 
192     /**
193      * Create a new {@link ChannelFuture} which is marked as succeeded already. So {@link ChannelFuture#isSuccess()}
194      * will return {@code true}. All {@link FutureListener} added to it will be notified directly. Also
195      * every call of blocking methods will just return without blocking.
196      */
197     ChannelFuture newSucceededFuture();
198 
199     /**
200      * Create a new {@link ChannelFuture} which is marked as failed already. So {@link ChannelFuture#isSuccess()}
201      * will return {@code false}. All {@link FutureListener} added to it will be notified directly. Also
202      * every call of blocking methods will just return without blocking.
203      */
204     ChannelFuture newFailedFuture(Throwable cause);
205 
206     /**
207      * Return a special ChannelPromise which can be reused for different operations.
208      * <p>
209      * It's only supported to use
210      * it for {@link Channel#write(Object, ChannelPromise)}.
211      * </p>
212      * <p>
213      * Be aware that the returned {@link ChannelPromise} will not support most operations and should only be used
214      * if you want to save an object allocation for every write operation. You will not be able to detect if the
215      * operation  was complete, only if it failed as the implementation will call
216      * {@link ChannelPipeline#fireExceptionCaught(Throwable)} in this case.
217      * </p>
218      * <strong>Be aware this is an expert feature and should be used with care!</strong>
219      */
220     ChannelPromise voidPromise();
221 
222     /**
223      * Request to bind to the given {@link SocketAddress} and notify the {@link ChannelFuture} once the operation
224      * completes, either because the operation was successful or because of an error.
225      * <p>
226      * This will result in having the
227      * {@link ChannelHandler#bind(ChannelHandlerContext, SocketAddress, ChannelPromise)} method
228      * called of the next {@link ChannelHandler} contained in the  {@link ChannelPipeline} of the
229      * {@link Channel}.
230      */
231     ChannelFuture bind(SocketAddress localAddress);
232 
233     /**
234      * Request to connect to the given {@link SocketAddress} and notify the {@link ChannelFuture} once the operation
235      * completes, either because the operation was successful or because of an error.
236      * <p>
237      * If the connection fails because of a connection timeout, the {@link ChannelFuture} will get failed with
238      * a {@link ConnectTimeoutException}. If it fails because of connection refused a {@link ConnectException}
239      * will be used.
240      * <p>
241      * This will result in having the
242      * {@link ChannelHandler#connect(ChannelHandlerContext, SocketAddress, SocketAddress, ChannelPromise)}
243      * method called of the next {@link ChannelHandler} contained in the  {@link ChannelPipeline} of the
244      * {@link Channel}.
245      */
246     ChannelFuture connect(SocketAddress remoteAddress);
247 
248     /**
249      * Request to connect to the given {@link SocketAddress} while bind to the localAddress and notify the
250      * {@link ChannelFuture} once the operation completes, either because the operation was successful or because of
251      * an error.
252      * <p>
253      * This will result in having the
254      * {@link ChannelHandler#connect(ChannelHandlerContext, SocketAddress, SocketAddress, ChannelPromise)}
255      * method called of the next {@link ChannelHandler} contained in the  {@link ChannelPipeline} of the
256      * {@link Channel}.
257      */
258     ChannelFuture connect(SocketAddress remoteAddress, SocketAddress localAddress);
259 
260     /**
261      * Request to disconnect from the remote peer and notify the {@link ChannelFuture} once the operation completes,
262      * either because the operation was successful or because of an error.
263      * <p>
264      * This will result in having the
265      * {@link ChannelHandler#disconnect(ChannelHandlerContext, ChannelPromise)}
266      * method called of the next {@link ChannelHandler} contained in the  {@link ChannelPipeline} of the
267      * {@link Channel}.
268      */
269     ChannelFuture disconnect();
270 
271     /**
272      * Request to close this {@link Channel} and notify the {@link ChannelFuture} once the operation completes,
273      * either because the operation was successful or because of
274      * an error.
275      *
276      * After it is closed it is not possible to reuse it again.
277      * <p>
278      * This will result in having the
279      * {@link ChannelHandler#close(ChannelHandlerContext, ChannelPromise)}
280      * method called of the next {@link ChannelHandler} contained in the  {@link ChannelPipeline} of the
281      * {@link Channel}.
282      */
283     ChannelFuture close();
284 
285     /**
286      * Request to deregister this {@link Channel} from its assigned {@link EventLoop} and notify the
287      * {@link ChannelFuture} once the operation completes, either because the operation was successful or because of
288      * an error.
289      * <p>
290      * This will result in having the
291      * {@link ChannelHandler#deregister(ChannelHandlerContext, ChannelPromise)}
292      * method called of the next {@link ChannelHandler} contained in the  {@link ChannelPipeline} of the
293      * {@link Channel}.
294      * <p>
295      * After this method completes (not the {@link ChannelFuture}!) one can not submit new tasks to the
296      * {@link Channel}'s {@link EventLoop} until the {@link Channel} is again registered with an {@link EventLoop}.
297      * Any attempt to do so will result in a {@link RejectedExecutionException} being thrown.
298      * Any tasks that were submitted before the call to {@link #deregister()} will finish before the
299      * {@link ChannelFuture} completes. Furthermore, periodic and delayed tasks will not be executed until the
300      * {@link Channel} is registered with an {@link EventLoop} again. Theses are tasks submitted
301      * to the {@link EventLoop} via one of the methods declared by {@link ScheduledExecutorService}.
302      * Please note that all of the above only applies to tasks created from within the deregistered {@link Channel}'s
303      * {@link ChannelHandler}s.
304      * <p>
305      * It's only safe to {@linkplain EventLoop#register(Channel)} the {@link Channel} with another (or the same)
306      * {@link EventLoop} after the {@link ChannelFuture} has completed.
307      */
308     ChannelFuture deregister();
309 
310     /**
311      * Request to bind to the given {@link SocketAddress} and notify the {@link ChannelFuture} once the operation
312      * completes, either because the operation was successful or because of an error.
313      *
314      * The given {@link ChannelPromise} will be notified.
315      * <p>
316      * This will result in having the
317      * {@link ChannelHandler#bind(ChannelHandlerContext, SocketAddress, ChannelPromise)} method
318      * called of the next {@link ChannelHandler} contained in the  {@link ChannelPipeline} of the
319      * {@link Channel}.
320      */
321     ChannelFuture bind(SocketAddress localAddress, ChannelPromise promise);
322 
323     /**
324      * Request to connect to the given {@link SocketAddress} and notify the {@link ChannelFuture} once the operation
325      * completes, either because the operation was successful or because of an error.
326      *
327      * The given {@link ChannelFuture} will be notified.
328      *
329      * <p>
330      * If the connection fails because of a connection timeout, the {@link ChannelFuture} will get failed with
331      * a {@link ConnectTimeoutException}. If it fails because of connection refused a {@link ConnectException}
332      * will be used.
333      * <p>
334      * This will result in having the
335      * {@link ChannelHandler#connect(ChannelHandlerContext, SocketAddress, SocketAddress, ChannelPromise)}
336      * method called of the next {@link ChannelHandler} contained in the  {@link ChannelPipeline} of the
337      * {@link Channel}.
338      */
339     ChannelFuture connect(SocketAddress remoteAddress, ChannelPromise promise);
340 
341     /**
342      * Request to connect to the given {@link SocketAddress} while bind to the localAddress and notify the
343      * {@link ChannelFuture} once the operation completes, either because the operation was successful or because of
344      * an error.
345      *
346      * The given {@link ChannelPromise} will be notified and also returned.
347      * <p>
348      * This will result in having the
349      * {@link ChannelHandler#connect(ChannelHandlerContext, SocketAddress, SocketAddress, ChannelPromise)}
350      * method called of the next {@link ChannelHandler} contained in the  {@link ChannelPipeline} of the
351      * {@link Channel}.
352      */
353     ChannelFuture connect(SocketAddress remoteAddress, SocketAddress localAddress, ChannelPromise promise);
354 
355     /**
356      * Request to disconnect from the remote peer and notify the {@link ChannelFuture} once the operation completes,
357      * either because the operation was successful or because of an error.
358      *
359      * The given {@link ChannelPromise} will be notified.
360      * <p>
361      * This will result in having the
362      * {@link ChannelHandler#disconnect(ChannelHandlerContext, ChannelPromise)}
363      * method called of the next {@link ChannelHandler} contained in the  {@link ChannelPipeline} of the
364      * {@link Channel}.
365      */
366     ChannelFuture disconnect(ChannelPromise promise);
367 
368     /**
369      * Request to close this {@link Channel} and notify the {@link ChannelFuture} once the operation completes,
370      * either because the operation was successful or because of
371      * an error.
372      *
373      * After it is closed it is not possible to reuse it again.
374      * The given {@link ChannelPromise} will be notified.
375      * <p>
376      * This will result in having the
377      * {@link ChannelHandler#close(ChannelHandlerContext, ChannelPromise)}
378      * method called of the next {@link ChannelHandler} contained in the  {@link ChannelPipeline} of the
379      * {@link Channel}.
380      */
381     ChannelFuture close(ChannelPromise promise);
382 
383     /**
384      * Request to deregister this {@link Channel} from its assigned {@link EventLoop} and notify the
385      * {@link ChannelPromise} once the operation completes, either because the operation was successful or because of
386      * an error.
387      * <p>
388      * This will result in having the
389      * {@link ChannelHandler#deregister(ChannelHandlerContext, ChannelPromise)}
390      * method called of the next {@link ChannelHandler} contained in the  {@link ChannelPipeline} of the
391      * {@link Channel}.
392      * <p>
393      * After this method completes (not the {@link ChannelPromise}!) one can not submit new tasks to the
394      * {@link Channel}'s {@link EventLoop} until the {@link Channel} is again registered with an {@link EventLoop}.
395      * Any attempt to do so will result in a {@link RejectedExecutionException} being thrown.
396      * Any tasks that were submitted before the call to {@link #deregister()} will finish before the
397      * {@link ChannelPromise} completes. Furthermore, periodic and delayed tasks will not be executed until the
398      * {@link Channel} is registered with an {@link EventLoop} again. Theses are tasks submitted
399      * to the {@link EventLoop} via one of the methods declared by {@link ScheduledExecutorService}.
400      * Please note that all of the above only applies to tasks created from within the deregistered {@link Channel}'s
401      * {@link ChannelHandler}s.
402      * <p>
403      * It's only safe to {@linkplain EventLoop#register(Channel)} the {@link Channel} with another (or the same)
404      * {@link EventLoop} after the {@link ChannelPromise} has completed.
405      */
406     ChannelFuture deregister(ChannelPromise promise);
407 
408     /**
409      * Request to Read data from the {@link Channel} into the first inbound buffer, triggers an
410      * {@link ChannelHandler#channelRead(ChannelHandlerContext, Object)} event if data was
411      * read, and triggers a
412      * {@link ChannelHandler#channelReadComplete(ChannelHandlerContext) channelReadComplete} event so the
413      * handler can decide to continue reading.  If there's a pending read operation already, this method does nothing.
414      * <p>
415      * This will result in having the
416      * {@link ChannelHandler#read(ChannelHandlerContext)}
417      * method called of the next {@link ChannelHandler} contained in the  {@link ChannelPipeline} of the
418      * {@link Channel}.
419      */
420     Channel read();
421 
422     /**
423      * Request to write a message via this {@link Channel} through the {@link ChannelPipeline}.
424      * This method will not request to actual flush, so be sure to call {@link #flush()}
425      * once you want to request to flush all pending data to the actual transport.
426      */
427     ChannelFuture write(Object msg);
428 
429     /**
430      * Request to write a message via this {@link Channel} through the {@link ChannelPipeline}.
431      * This method will not request to actual flush, so be sure to call {@link #flush()}
432      * once you want to request to flush all pending data to the actual transport.
433      */
434     ChannelFuture write(Object msg, ChannelPromise promise);
435 
436     /**
437      * Request to flush all pending messages.
438      */
439     Channel flush();
440 
441     /**
442      * Shortcut for call {@link #write(Object, ChannelPromise)} and {@link #flush()}.
443      */
444     ChannelFuture writeAndFlush(Object msg, ChannelPromise promise);
445 
446     /**
447      * Shortcut for call {@link #write(Object)} and {@link #flush()}.
448      */
449     ChannelFuture writeAndFlush(Object msg);
450 
451     /**
452      * <em>Unsafe</em> operations that should <em>never</em> be called from user-code. These methods
453      * are only provided to implement the actual transport, and must be invoked from an I/O thread except for the
454      * following methods:
455      * <ul>
456      *   <li>{@link #invoker()}</li>
457      *   <li>{@link #localAddress()}</li>
458      *   <li>{@link #remoteAddress()}</li>
459      *   <li>{@link #closeForcibly()}</li>
460      *   <li>{@link #register(EventLoop, ChannelPromise)}</li>
461      *   <li>{@link #deregister(ChannelPromise)}</li>
462      *   <li>{@link #voidPromise()}</li>
463      * </ul>
464      */
465     interface Unsafe {
466 
467         /**
468          * Return the assigned {@link RecvByteBufAllocator.Handle} which will be used to allocate {@link ByteBuf}'s when
469          * receiving data.
470          */
471         RecvByteBufAllocator.Handle recvBufAllocHandle();
472 
473         /**
474          * Returns the {@link ChannelHandlerInvoker} which is used by default unless specified by a user.
475          */
476         ChannelHandlerInvoker invoker();
477 
478         /**
479          * Return the {@link SocketAddress} to which is bound local or
480          * {@code null} if none.
481          */
482         SocketAddress localAddress();
483 
484         /**
485          * Return the {@link SocketAddress} to which is bound remote or
486          * {@code null} if none is bound yet.
487          */
488         SocketAddress remoteAddress();
489 
490         /**
491          * Register the {@link Channel} of the {@link ChannelPromise} and notify
492          * the {@link ChannelFuture} once the registration was complete.
493          * <p>
494          * It's only safe to submit a new task to the {@link EventLoop} from within a
495          * {@link ChannelHandler} once the {@link ChannelPromise} succeeded. Otherwise
496          * the task may or may not be rejected.
497          * </p>
498          */
499         void register(EventLoop eventLoop, ChannelPromise promise);
500 
501         /**
502          * Bind the {@link SocketAddress} to the {@link Channel} of the {@link ChannelPromise} and notify
503          * it once its done.
504          */
505         void bind(SocketAddress localAddress, ChannelPromise promise);
506 
507         /**
508          * Connect the {@link Channel} of the given {@link ChannelFuture} with the given remote {@link SocketAddress}.
509          * If a specific local {@link SocketAddress} should be used it need to be given as argument. Otherwise just
510          * pass {@code null} to it.
511          *
512          * The {@link ChannelPromise} will get notified once the connect operation was complete.
513          */
514         void connect(SocketAddress remoteAddress, SocketAddress localAddress, ChannelPromise promise);
515 
516         /**
517          * Disconnect the {@link Channel} of the {@link ChannelFuture} and notify the {@link ChannelPromise} once the
518          * operation was complete.
519          */
520         void disconnect(ChannelPromise promise);
521 
522         /**
523          * Close the {@link Channel} of the {@link ChannelPromise} and notify the {@link ChannelPromise} once the
524          * operation was complete.
525          */
526         void close(ChannelPromise promise);
527 
528         /**
529          * Closes the {@link Channel} immediately without firing any events.  Probably only useful
530          * when registration attempt failed.
531          */
532         void closeForcibly();
533 
534         /**
535          * Deregister the {@link Channel} of the {@link ChannelPromise} from {@link EventLoop} and notify the
536          * {@link ChannelPromise} once the operation was complete.
537          */
538         void deregister(ChannelPromise promise);
539 
540         /**
541          * Schedules a read operation that fills the inbound buffer of the first {@link ChannelHandler} in the
542          * {@link ChannelPipeline}.  If there's already a pending read operation, this method does nothing.
543          */
544         void beginRead();
545 
546         /**
547          * Schedules a write operation.
548          */
549         void write(Object msg, ChannelPromise promise);
550 
551         /**
552          * Flush out all write operations scheduled via {@link #write(Object, ChannelPromise)}.
553          */
554         void flush();
555 
556         /**
557          * Return a special ChannelPromise which can be reused and passed to the operations in {@link Unsafe}.
558          * It will never be notified of a success or error and so is only a placeholder for operations
559          * that take a {@link ChannelPromise} as argument but for which you not want to get notified.
560          */
561         ChannelPromise voidPromise();
562 
563         /**
564          * Returns the {@link ChannelOutboundBuffer} of the {@link Channel} where the pending write requests are stored.
565          */
566         ChannelOutboundBuffer outboundBuffer();
567     }
568 }