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 default boolean isWritable() { 165 ChannelOutboundBuffer buf = unsafe().outboundBuffer(); 166 return buf != null && buf.isWritable(); 167 } 168 169 /** 170 * Get how many bytes can be written until {@link #isWritable()} returns {@code false}. 171 * This quantity will always be non-negative. If {@link #isWritable()} is {@code false} then 0. 172 * 173 * {@link WriteBufferWaterMark} can be used to define writability settings. 174 */ 175 default long bytesBeforeUnwritable() { 176 ChannelOutboundBuffer buf = unsafe().outboundBuffer(); 177 // isWritable() is currently assuming if there is no outboundBuffer then the channel is not writable. 178 // We should be consistent with that here. 179 return buf != null ? buf.bytesBeforeUnwritable() : 0; 180 } 181 182 /** 183 * Get how many bytes must be drained from underlying buffers until {@link #isWritable()} returns {@code true}. 184 * This quantity will always be non-negative. If {@link #isWritable()} is {@code true} then 0. 185 * 186 * {@link WriteBufferWaterMark} can be used to define writability settings. 187 */ 188 default long bytesBeforeWritable() { 189 ChannelOutboundBuffer buf = unsafe().outboundBuffer(); 190 // isWritable() is currently assuming if there is no outboundBuffer then the channel is not writable. 191 // We should be consistent with that here. 192 return buf != null ? buf.bytesBeforeWritable() : Long.MAX_VALUE; 193 } 194 195 /** 196 * Returns an <em>internal-use-only</em> object that provides unsafe operations. 197 */ 198 Unsafe unsafe(); 199 200 /** 201 * Return the assigned {@link ChannelPipeline}. 202 */ 203 ChannelPipeline pipeline(); 204 205 /** 206 * Return the assigned {@link ByteBufAllocator} which will be used to allocate {@link ByteBuf}s. 207 */ 208 default ByteBufAllocator alloc() { 209 return config().getAllocator(); 210 } 211 212 @Override 213 default Channel read() { 214 pipeline().read(); 215 return this; 216 } 217 218 @Override 219 default Channel flush() { 220 pipeline().flush(); 221 return this; 222 } 223 224 @Override 225 default ChannelFuture writeAndFlush(Object msg) { 226 return pipeline().writeAndFlush(msg); 227 } 228 229 @Override 230 default ChannelFuture writeAndFlush(Object msg, ChannelPromise promise) { 231 return pipeline().writeAndFlush(msg, promise); 232 } 233 234 @Override 235 default ChannelFuture write(Object msg, ChannelPromise promise) { 236 return pipeline().write(msg, promise); 237 } 238 239 @Override 240 default ChannelFuture write(Object msg) { 241 return pipeline().write(msg); 242 } 243 244 @Override 245 default ChannelFuture deregister(ChannelPromise promise) { 246 return pipeline().deregister(promise); 247 } 248 249 @Override 250 default ChannelFuture close(ChannelPromise promise) { 251 return pipeline().close(promise); 252 } 253 254 @Override 255 default ChannelFuture disconnect(ChannelPromise promise) { 256 return pipeline().disconnect(promise); 257 } 258 259 @Override 260 default ChannelFuture connect(SocketAddress remoteAddress, SocketAddress localAddress, ChannelPromise promise) { 261 return pipeline().connect(remoteAddress, localAddress, promise); 262 } 263 264 @Override 265 default ChannelFuture connect(SocketAddress remoteAddress, ChannelPromise promise) { 266 return pipeline().connect(remoteAddress, promise); 267 } 268 269 @Override 270 default ChannelFuture bind(SocketAddress localAddress, ChannelPromise promise) { 271 return pipeline().bind(localAddress, promise); 272 } 273 274 @Override 275 default ChannelFuture deregister() { 276 return pipeline().deregister(); 277 } 278 279 @Override 280 default ChannelFuture close() { 281 return pipeline().close(); 282 } 283 284 @Override 285 default ChannelFuture disconnect() { 286 return pipeline().disconnect(); 287 } 288 289 @Override 290 default ChannelFuture connect(SocketAddress remoteAddress, SocketAddress localAddress) { 291 return pipeline().connect(remoteAddress, localAddress); 292 } 293 294 @Override 295 default ChannelFuture connect(SocketAddress remoteAddress) { 296 return pipeline().connect(remoteAddress); 297 } 298 299 @Override 300 default ChannelFuture bind(SocketAddress localAddress) { 301 return pipeline().bind(localAddress); 302 } 303 304 @Override 305 default ChannelPromise newPromise() { 306 return pipeline().newPromise(); 307 } 308 309 @Override 310 default ChannelProgressivePromise newProgressivePromise() { 311 return pipeline().newProgressivePromise(); 312 } 313 314 @Override 315 default ChannelFuture newSucceededFuture() { 316 return pipeline().newSucceededFuture(); 317 } 318 319 @Override 320 default ChannelFuture newFailedFuture(Throwable cause) { 321 return pipeline().newFailedFuture(cause); 322 } 323 324 @Override 325 default ChannelPromise voidPromise() { 326 return pipeline().voidPromise(); 327 } 328 329 /** 330 * <em>Unsafe</em> operations that should <em>never</em> be called from user-code. These methods 331 * are only provided to implement the actual transport, and must be invoked from an I/O thread except for the 332 * following methods: 333 * <ul> 334 * <li>{@link #localAddress()}</li> 335 * <li>{@link #remoteAddress()}</li> 336 * <li>{@link #closeForcibly()}</li> 337 * <li>{@link #register(EventLoop, ChannelPromise)}</li> 338 * <li>{@link #deregister(ChannelPromise)}</li> 339 * <li>{@link #voidPromise()}</li> 340 * </ul> 341 */ 342 interface Unsafe { 343 344 /** 345 * Return the assigned {@link RecvByteBufAllocator.Handle} which will be used to allocate {@link ByteBuf}'s when 346 * receiving data. 347 */ 348 RecvByteBufAllocator.Handle recvBufAllocHandle(); 349 350 /** 351 * Return the {@link SocketAddress} to which is bound local or 352 * {@code null} if none. 353 */ 354 SocketAddress localAddress(); 355 356 /** 357 * Return the {@link SocketAddress} to which is bound remote or 358 * {@code null} if none is bound yet. 359 */ 360 SocketAddress remoteAddress(); 361 362 /** 363 * Register the {@link Channel} of the {@link ChannelPromise} and notify 364 * the {@link ChannelFuture} once the registration was complete. 365 */ 366 void register(EventLoop eventLoop, ChannelPromise promise); 367 368 /** 369 * Bind the {@link SocketAddress} to the {@link Channel} of the {@link ChannelPromise} and notify 370 * it once its done. 371 */ 372 void bind(SocketAddress localAddress, ChannelPromise promise); 373 374 /** 375 * Connect the {@link Channel} of the given {@link ChannelFuture} with the given remote {@link SocketAddress}. 376 * If a specific local {@link SocketAddress} should be used it need to be given as argument. Otherwise just 377 * pass {@code null} to it. 378 * 379 * The {@link ChannelPromise} will get notified once the connect operation was complete. 380 */ 381 void connect(SocketAddress remoteAddress, SocketAddress localAddress, ChannelPromise promise); 382 383 /** 384 * Disconnect the {@link Channel} of the {@link ChannelFuture} and notify the {@link ChannelPromise} once the 385 * operation was complete. 386 */ 387 void disconnect(ChannelPromise promise); 388 389 /** 390 * Close the {@link Channel} of the {@link ChannelPromise} and notify the {@link ChannelPromise} once the 391 * operation was complete. 392 */ 393 void close(ChannelPromise promise); 394 395 /** 396 * Closes the {@link Channel} immediately without firing any events. Probably only useful 397 * when registration attempt failed. 398 */ 399 void closeForcibly(); 400 401 /** 402 * Deregister the {@link Channel} of the {@link ChannelPromise} from {@link EventLoop} and notify the 403 * {@link ChannelPromise} once the operation was complete. 404 */ 405 void deregister(ChannelPromise promise); 406 407 /** 408 * Schedules a read operation that fills the inbound buffer of the first {@link ChannelInboundHandler} in the 409 * {@link ChannelPipeline}. If there's already a pending read operation, this method does nothing. 410 */ 411 void beginRead(); 412 413 /** 414 * Schedules a write operation. 415 */ 416 void write(Object msg, ChannelPromise promise); 417 418 /** 419 * Flush out all write operations scheduled via {@link #write(Object, ChannelPromise)}. 420 */ 421 void flush(); 422 423 /** 424 * Return a special ChannelPromise which can be reused and passed to the operations in {@link Unsafe}. 425 * It will never be notified of a success or error and so is only a placeholder for operations 426 * that take a {@link ChannelPromise} as argument but for which you not want to get notified. 427 */ 428 ChannelPromise voidPromise(); 429 430 /** 431 * Returns the {@link ChannelOutboundBuffer} of the {@link Channel} where the pending write requests are stored. 432 */ 433 ChannelOutboundBuffer outboundBuffer(); 434 } 435 }