查看本类的 API文档回源码主页即时通讯网 - 即时通讯开发者社区!
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.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  
26  import java.net.InetSocketAddress;
27  import java.net.SocketAddress;
28  
29  
30  /**
31   * A nexus to a network socket or a component which is capable of I/O
32   * operations such as read, write, connect, and bind.
33   * <p>
34   * A channel provides a user:
35   * <ul>
36   * <li>the current state of the channel (e.g. is it open? is it connected?),</li>
37   * <li>the {@linkplain ChannelConfig configuration parameters} of the channel (e.g. receive buffer size),</li>
38   * <li>the I/O operations that the channel supports (e.g. read, write, connect, and bind), and</li>
39   * <li>the {@link ChannelPipeline} which handles all I/O events and requests
40   *     associated with the channel.</li>
41   * </ul>
42   *
43   * <h3>All I/O operations are asynchronous.</h3>
44   * <p>
45   * All I/O operations in Netty are asynchronous.  It means any I/O calls will
46   * return immediately with no guarantee that the requested I/O operation has
47   * been completed at the end of the call.  Instead, you will be returned with
48   * a {@link ChannelFuture} instance which will notify you when the requested I/O
49   * operation has succeeded, failed, or canceled.
50   *
51   * <h3>Channels are hierarchical</h3>
52   * <p>
53   * A {@link Channel} can have a {@linkplain #parent() parent} depending on
54   * how it was created.  For instance, a {@link SocketChannel}, that was accepted
55   * by {@link ServerSocketChannel}, will return the {@link ServerSocketChannel}
56   * as its parent on {@link #parent()}.
57   * <p>
58   * The semantics of the hierarchical structure depends on the transport
59   * implementation where the {@link Channel} belongs to.  For example, you could
60   * write a new {@link Channel} implementation that creates the sub-channels that
61   * share one socket connection, as <a href="http://beepcore.org/">BEEP</a> and
62   * <a href="https://en.wikipedia.org/wiki/Secure_Shell">SSH</a> do.
63   *
64   * <h3>Downcast to access transport-specific operations</h3>
65   * <p>
66   * Some transports exposes additional operations that is specific to the
67   * transport.  Down-cast the {@link Channel} to sub-type to invoke such
68   * operations.  For example, with the old I/O datagram transport, multicast
69   * join / leave operations are provided by {@link DatagramChannel}.
70   *
71   * <h3>Release resources</h3>
72   * <p>
73   * It is important to call {@link #close()} or {@link #close(ChannelPromise)} to release all
74   * resources once you are done with the {@link Channel}. This ensures all resources are
75   * released in a proper way, i.e. filehandles.
76   */
77  public interface Channel extends AttributeMap, ChannelOutboundInvoker, Comparable<Channel> {
78  
79      /**
80       * Returns the globally unique identifier of this {@link Channel}.
81       */
82      ChannelId id();
83  
84      /**
85       * Return the {@link EventLoop} this {@link Channel} was registered to.
86       */
87      EventLoop eventLoop();
88  
89      /**
90       * Returns the parent of this channel.
91       *
92       * @return the parent channel.
93       *         {@code null} if this channel does not have a parent channel.
94       */
95      Channel parent();
96  
97      /**
98       * Returns the configuration of this channel.
99       */
100     ChannelConfig config();
101 
102     /**
103      * Returns {@code true} if the {@link Channel} is open and may get active later
104      */
105     boolean isOpen();
106 
107     /**
108      * Returns {@code true} if the {@link Channel} is registered with an {@link EventLoop}.
109      */
110     boolean isRegistered();
111 
112     /**
113      * Return {@code true} if the {@link Channel} is active and so connected.
114      */
115     boolean isActive();
116 
117     /**
118      * Return the {@link ChannelMetadata} of the {@link Channel} which describe the nature of the {@link Channel}.
119      */
120     ChannelMetadata metadata();
121 
122     /**
123      * Returns the local address where this channel is bound to.  The returned
124      * {@link SocketAddress} is supposed to be down-cast into more concrete
125      * type such as {@link InetSocketAddress} to retrieve the detailed
126      * information.
127      *
128      * @return the local address of this channel.
129      *         {@code null} if this channel is not bound.
130      */
131     SocketAddress localAddress();
132 
133     /**
134      * Returns the remote address where this channel is connected to.  The
135      * returned {@link SocketAddress} is supposed to be down-cast into more
136      * concrete type such as {@link InetSocketAddress} to retrieve the detailed
137      * information.
138      *
139      * @return the remote address of this channel.
140      *         {@code null} if this channel is not connected.
141      *         If this channel is not connected but it can receive messages
142      *         from arbitrary remote addresses (e.g. {@link DatagramChannel},
143      *         use {@link DatagramPacket#recipient()} to determine
144      *         the origination of the received message as this method will
145      *         return {@code null}.
146      */
147     SocketAddress remoteAddress();
148 
149     /**
150      * Returns the {@link ChannelFuture} which will be notified when this
151      * channel is closed.  This method always returns the same future instance.
152      */
153     ChannelFuture closeFuture();
154 
155     /**
156      * Returns {@code true} if and only if the I/O thread will perform the
157      * requested write operation immediately.  Any write requests made when
158      * this method returns {@code false} are queued until the I/O thread is
159      * ready to process the queued write requests.
160      *
161      * {@link WriteBufferWaterMark} can be used to configure on which condition
162      * the write buffer would cause this channel to change writability.
163      */
164     boolean isWritable();
165 
166     /**
167      * Get how many bytes can be written until {@link #isWritable()} returns {@code false}.
168      * This quantity will always be non-negative. If {@link #isWritable()} is {@code false} then 0.
169      *
170      * {@link WriteBufferWaterMark} can be used to define writability settings.
171      */
172     long bytesBeforeUnwritable();
173 
174     /**
175      * Get how many bytes must be drained from underlying buffers until {@link #isWritable()} returns {@code true}.
176      * This quantity will always be non-negative. If {@link #isWritable()} is {@code true} then 0.
177      *
178      * {@link WriteBufferWaterMark} can be used to define writability settings.
179      */
180     long bytesBeforeWritable();
181 
182     /**
183      * Returns an <em>internal-use-only</em> object that provides unsafe operations.
184      */
185     Unsafe unsafe();
186 
187     /**
188      * Return the assigned {@link ChannelPipeline}.
189      */
190     ChannelPipeline pipeline();
191 
192     /**
193      * Return the assigned {@link ByteBufAllocator} which will be used to allocate {@link ByteBuf}s.
194      */
195     ByteBufAllocator alloc();
196 
197     @Override
198     Channel read();
199 
200     @Override
201     Channel flush();
202 
203     /**
204      * <em>Unsafe</em> operations that should <em>never</em> be called from user-code. These methods
205      * are only provided to implement the actual transport, and must be invoked from an I/O thread except for the
206      * following methods:
207      * <ul>
208      *   <li>{@link #localAddress()}</li>
209      *   <li>{@link #remoteAddress()}</li>
210      *   <li>{@link #closeForcibly()}</li>
211      *   <li>{@link #register(EventLoop, ChannelPromise)}</li>
212      *   <li>{@link #deregister(ChannelPromise)}</li>
213      *   <li>{@link #voidPromise()}</li>
214      * </ul>
215      */
216     interface Unsafe {
217 
218         /**
219          * Return the assigned {@link RecvByteBufAllocator.Handle} which will be used to allocate {@link ByteBuf}'s when
220          * receiving data.
221          */
222         RecvByteBufAllocator.Handle recvBufAllocHandle();
223 
224         /**
225          * Return the {@link SocketAddress} to which is bound local or
226          * {@code null} if none.
227          */
228         SocketAddress localAddress();
229 
230         /**
231          * Return the {@link SocketAddress} to which is bound remote or
232          * {@code null} if none is bound yet.
233          */
234         SocketAddress remoteAddress();
235 
236         /**
237          * Register the {@link Channel} of the {@link ChannelPromise} and notify
238          * the {@link ChannelFuture} once the registration was complete.
239          */
240         void register(EventLoop eventLoop, ChannelPromise promise);
241 
242         /**
243          * Bind the {@link SocketAddress} to the {@link Channel} of the {@link ChannelPromise} and notify
244          * it once its done.
245          */
246         void bind(SocketAddress localAddress, ChannelPromise promise);
247 
248         /**
249          * Connect the {@link Channel} of the given {@link ChannelFuture} with the given remote {@link SocketAddress}.
250          * If a specific local {@link SocketAddress} should be used it need to be given as argument. Otherwise just
251          * pass {@code null} to it.
252          *
253          * The {@link ChannelPromise} will get notified once the connect operation was complete.
254          */
255         void connect(SocketAddress remoteAddress, SocketAddress localAddress, ChannelPromise promise);
256 
257         /**
258          * Disconnect the {@link Channel} of the {@link ChannelFuture} and notify the {@link ChannelPromise} once the
259          * operation was complete.
260          */
261         void disconnect(ChannelPromise promise);
262 
263         /**
264          * Close the {@link Channel} of the {@link ChannelPromise} and notify the {@link ChannelPromise} once the
265          * operation was complete.
266          */
267         void close(ChannelPromise promise);
268 
269         /**
270          * Closes the {@link Channel} immediately without firing any events.  Probably only useful
271          * when registration attempt failed.
272          */
273         void closeForcibly();
274 
275         /**
276          * Deregister the {@link Channel} of the {@link ChannelPromise} from {@link EventLoop} and notify the
277          * {@link ChannelPromise} once the operation was complete.
278          */
279         void deregister(ChannelPromise promise);
280 
281         /**
282          * Schedules a read operation that fills the inbound buffer of the first {@link ChannelInboundHandler} in the
283          * {@link ChannelPipeline}.  If there's already a pending read operation, this method does nothing.
284          */
285         void beginRead();
286 
287         /**
288          * Schedules a write operation.
289          */
290         void write(Object msg, ChannelPromise promise);
291 
292         /**
293          * Flush out all write operations scheduled via {@link #write(Object, ChannelPromise)}.
294          */
295         void flush();
296 
297         /**
298          * Return a special ChannelPromise which can be reused and passed to the operations in {@link Unsafe}.
299          * It will never be notified of a success or error and so is only a placeholder for operations
300          * that take a {@link ChannelPromise} as argument but for which you not want to get notified.
301          */
302         ChannelPromise voidPromise();
303 
304         /**
305          * Returns the {@link ChannelOutboundBuffer} of the {@link Channel} where the pending write requests are stored.
306          */
307         ChannelOutboundBuffer outboundBuffer();
308     }
309 }