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    *   https://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.netty5.channel;
17  
18  import io.netty5.buffer.api.Buffer;
19  import io.netty5.buffer.api.BufferAllocator;
20  import io.netty5.channel.socket.DatagramChannel;
21  import io.netty5.channel.socket.DatagramPacket;
22  import io.netty5.channel.socket.ServerSocketChannel;
23  import io.netty5.channel.socket.SocketChannel;
24  import io.netty5.util.AttributeKey;
25  import io.netty5.util.AttributeMap;
26  import io.netty5.util.concurrent.Future;
27  
28  import java.net.InetSocketAddress;
29  import java.net.SocketAddress;
30  
31  /**
32   * A nexus to a network socket or a component which is capable of I/O
33   * operations such as read, write, connect, and bind.
34   * <p>
35   * A channel provides a user:
36   * <ul>
37   * <li>the current state of the channel (e.g. is it open? is it connected?),</li>
38   * <li>the configuration parameters of the channel (e.g. receive buffer size),</li>
39   * <li>the I/O operations that the channel supports (e.g. read, write, connect, and bind), and</li>
40   * <li>the {@link ChannelPipeline} which handles all I/O events and requests
41   *     associated with the channel.</li>
42   * </ul>
43   *
44   * <h3>All I/O operations are asynchronous.</h3>
45   * <p>
46   * All I/O operations in Netty are asynchronous.  It means any I/O calls will
47   * return immediately with no guarantee that the requested I/O operation has
48   * been completed at the end of the call.  Instead, you will be returned with
49   * a {@link Future} instance which will notify you when the requested I/O
50   * operation has succeeded, failed, or canceled.
51   *
52   * <h3>Channels are hierarchical</h3>
53   * <p>
54   * A {@link Channel} can have a {@linkplain #parent() parent} depending on
55   * how it was created.  For instance, a {@link SocketChannel}, that was accepted
56   * by {@link ServerSocketChannel}, will return the {@link ServerSocketChannel}
57   * as its parent on {@link #parent()}.
58   * <p>
59   * The semantics of the hierarchical structure depends on the transport
60   * implementation where the {@link Channel} belongs to.  For example, you could
61   * write a new {@link Channel} implementation that creates the sub-channels that
62   * share one socket connection, as <a href="http://beepcore.org/">BEEP</a> and
63   * <a href="https://en.wikipedia.org/wiki/Secure_Shell">SSH</a> do.
64   *
65   * <h3>Downcast to access transport-specific operations</h3>
66   * <p>
67   * Some transports exposes additional operations that is specific to the
68   * transport.  Down-cast the {@link Channel} to sub-type to invoke such
69   * operations.  For example, with the old I/O datagram transport, multicast
70   * join / leave operations are provided by {@link DatagramChannel}.
71   *
72   *
73   * <h3>Storing stateful information</h3>
74   *
75   * {@link #attr(AttributeKey)} allow you to
76   * store and access stateful information that is related with a handler and its
77   * context.  Please refer to {@link ChannelHandler} to learn various recommended
78   * ways to manage stateful information.
79   *
80   * <h3>Release resources</h3>
81   * <p>
82   * It is important to call {@link #close()} to release all
83   * resources once you are done with the {@link Channel}. This ensures all resources are
84   * released in a proper way, i.e. filehandles.
85   *
86   * <h3>Configuration / Option map</h3>
87   *
88   * An option map property is a dynamic write-only property which allows
89   * the configuration of a {@link Channel} without down-casting.
90   * To update an option map, please call {@link #setOption(ChannelOption, Object)}.
91   * <p>
92   * All {@link Channel} types have the following options:
93   *
94   * <table border="1" cellspacing="0" cellpadding="6">
95   * <tr>
96   * <th>Name</th>
97   * </tr><tr>
98   * <td>{@link ChannelOption#CONNECT_TIMEOUT_MILLIS}</td>
99   * </tr><tr>
100  * <td>{@link ChannelOption#WRITE_SPIN_COUNT}</td>
101  * </tr><tr>
102  * <td>{@link ChannelOption#WRITE_BUFFER_WATER_MARK}</td>
103  * </tr><tr>
104  * <td>{@link ChannelOption#BUFFER_ALLOCATOR}</td>
105  * </tr><tr>
106  * <td>{@link ChannelOption#AUTO_READ}</td>
107  * </tr><tr>
108  * <td>{@link ChannelOption#ALLOW_HALF_CLOSURE}</td>
109  * </tr><tr>
110  * <td>{@link ChannelOption#MAX_MESSAGES_PER_WRITE}</td>
111  * </tr><tr>
112  * <td>{@link ChannelOption#ALLOW_HALF_CLOSURE}</td>
113  * </tr>
114  * </table>
115  * <p>
116  * More options are available in the sub-types of {@link Channel}. For
117  * example, you can configure the parameters which are specific to a TCP/IP
118  * socket as explained in {@link SocketChannel}.
119  */
120 public interface Channel extends AttributeMap, ChannelOutboundInvoker, Comparable<Channel>, IoHandle {
121 
122     /**
123      * Returns the globally unique identifier of this {@link Channel}.
124      */
125     ChannelId id();
126 
127     /**
128      * Return the {@link EventLoop} this {@link Channel} was registered to.
129      */
130     @Override
131     EventLoop executor();
132 
133     /**
134      * Returns the parent of this channel.
135      *
136      * @return the parent channel.
137      *         {@code null} if this channel does not have a parent channel.
138      */
139     Channel parent();
140 
141     /**
142      * Return the value of the given {@link ChannelOption}
143      *
144      * @param option                            the {@link ChannelOption}.
145      * @return                                  the value for the {@link ChannelOption}
146      * @param <T>                               the type of the value.
147      * @throws ChannelException                 thrown on error.
148      * @throws UnsupportedOperationException    if the {@link ChannelOption} is not supported.
149      */
150     <T> T getOption(ChannelOption<T> option);
151 
152     /**
153      * Sets a configuration property with the specified name and value.
154      *
155      * @param option                            the {@link ChannelOption}.
156      * @param value                             the value for the {@link ChannelOption}
157      * @return                                  itself.
158      * @param <T>                               the type of the value.
159      * @throws ChannelException                 thrown on error.
160      * @throws UnsupportedOperationException    if the {@link ChannelOption} is not supported.
161      */
162     <T> Channel setOption(ChannelOption<T> option, T value);
163 
164     /**
165      * Returns {@code true} if the given {@link ChannelOption} is supported by this {@link Channel} implementation.
166      * If this methods returns {@code false}, calls to {@link #setOption(ChannelOption, Object)}
167      * and {@link #getOption(ChannelOption)} with the {@link ChannelOption} will throw an
168      * {@link UnsupportedOperationException}.
169      *
170      * @param option    the option.
171      * @return          {@code} true if supported, {@code false} otherwise.
172      */
173     boolean isOptionSupported(ChannelOption<?> option);
174 
175     /**
176      * Returns {@code true} if the {@link Channel} is open and may get active later
177      */
178     boolean isOpen();
179 
180     /**
181      * Return {@code true} if the {@link Channel} is active and so connected.
182      */
183     boolean isActive();
184 
185     /**
186      * Returns {@code true} if the {@link ChannelShutdownDirection} of the {@link Channel} was shutdown before.
187      */
188     boolean isShutdown(ChannelShutdownDirection direction);
189 
190     /**
191      * Return the {@link ChannelMetadata} of the {@link Channel} which describe the nature of the {@link Channel}.
192      */
193     ChannelMetadata metadata();
194 
195     /**
196      * Returns the local address where this channel is bound to.  The returned
197      * {@link SocketAddress} is supposed to be down-cast into more concrete
198      * type such as {@link InetSocketAddress} to retrieve the detailed
199      * information.
200      *
201      * @return the local address of this channel.
202      *         {@code null} if this channel is not bound.
203      */
204     SocketAddress localAddress();
205 
206     /**
207      * Returns the remote address where this channel is connected to.  The
208      * returned {@link SocketAddress} is supposed to be down-cast into more
209      * concrete type such as {@link InetSocketAddress} to retrieve the detailed
210      * information.
211      *
212      * @return the remote address of this channel.
213      *         {@code null} if this channel is not connected.
214      *         If this channel is not connected but it can receive messages
215      *         from arbitrary remote addresses (e.g. {@link DatagramChannel},
216      *         use {@link DatagramPacket#recipient()} to determine
217      *         the origination of the received message as this method will
218      *         return {@code null}.
219      */
220     SocketAddress remoteAddress();
221 
222     /**
223      * Returns the {@link Future} which will be notified when this
224      * channel is closed.  This method always returns the same future instance.
225      */
226     Future<Void> closeFuture();
227 
228     /**
229      * Returns {@code true} if and only if the I/O thread will perform the
230      * requested flush operation immediately. Any write requests made when
231      * this method returns {@code false} are queued until the I/O thread is
232      * ready to process the queued write requests.
233      */
234     default boolean isWritable() {
235         return writableBytes() > 0;
236     }
237 
238     /**
239      * Returns how many bytes can be written before the {@link Channel} becomes 'unwritable'.
240      * Once a {@link Channel} becomes unwritable, all messages will be queued until the I/O thread is
241      * ready to process the queued write requests.
242      *
243      * @return the number of bytes that can be written before the {@link Channel} becomes unwritable.
244      */
245     long writableBytes();
246 
247     /**
248      * Return the assigned {@link ChannelPipeline}.
249      */
250     ChannelPipeline pipeline();
251 
252     /**
253      * Return the assigned {@link BufferAllocator} which will be used to allocate {@link Buffer}s.
254      */
255     BufferAllocator bufferAllocator();
256 
257     @Override
258     default Channel read() {
259         pipeline().read();
260         return this;
261     }
262 
263     @Override
264     default Future<Void> bind(SocketAddress localAddress) {
265         return pipeline().bind(localAddress);
266     }
267 
268     @Override
269     default Future<Void> connect(SocketAddress remoteAddress) {
270         return pipeline().connect(remoteAddress);
271     }
272 
273     @Override
274     default Future<Void> connect(SocketAddress remoteAddress, SocketAddress localAddress) {
275         return pipeline().connect(remoteAddress, localAddress);
276     }
277 
278     @Override
279     default Future<Void> disconnect() {
280         return pipeline().disconnect();
281     }
282 
283     @Override
284     default Future<Void> close() {
285         return pipeline().close();
286     }
287 
288     @Override
289     default Future<Void> shutdown(ChannelShutdownDirection direction) {
290         return pipeline().shutdown(direction);
291     }
292 
293     @Override
294     default Future<Void> register() {
295         return pipeline().register();
296     }
297 
298     @Override
299     default Future<Void> deregister() {
300         return pipeline().deregister();
301     }
302 
303     @Override
304     default Future<Void> write(Object msg) {
305         return pipeline().write(msg);
306     }
307 
308     @Override
309     default Future<Void> writeAndFlush(Object msg) {
310         return pipeline().writeAndFlush(msg);
311     }
312 
313     @Override
314     default Channel flush() {
315         pipeline().flush();
316         return this;
317     }
318 
319     @Override
320     default Future<Void> sendOutboundEvent(Object event) {
321         return pipeline().sendOutboundEvent(event);
322     }
323 }