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 /** 213 * Return the value of the given {@link ChannelOption} 214 */ 215 default <T> T getOption(ChannelOption<T> option) { 216 return config().getOption(option); 217 } 218 219 /** 220 * Sets a configuration property with the specified name and value. 221 * To override this method properly, you must call the super class: 222 * <pre> 223 * public boolean setOption(ChannelOption<T> option, T value) { 224 * if (super.setOption(option, value)) { 225 * return true; 226 * } 227 * 228 * if (option.equals(additionalOption)) { 229 * .... 230 * return true; 231 * } 232 * 233 * return false; 234 * } 235 * </pre> 236 * 237 * @return {@code true} if and only if the property has been set 238 */ 239 default <T> boolean setOption(ChannelOption<T> option, T value) { 240 return config().setOption(option, value); 241 } 242 243 @Override 244 default Channel read() { 245 pipeline().read(); 246 return this; 247 } 248 249 @Override 250 default Channel flush() { 251 pipeline().flush(); 252 return this; 253 } 254 255 @Override 256 default ChannelFuture writeAndFlush(Object msg) { 257 return pipeline().writeAndFlush(msg); 258 } 259 260 @Override 261 default ChannelFuture writeAndFlush(Object msg, ChannelPromise promise) { 262 return pipeline().writeAndFlush(msg, promise); 263 } 264 265 @Override 266 default ChannelFuture write(Object msg, ChannelPromise promise) { 267 return pipeline().write(msg, promise); 268 } 269 270 @Override 271 default ChannelFuture write(Object msg) { 272 return pipeline().write(msg); 273 } 274 275 @Override 276 default ChannelFuture deregister(ChannelPromise promise) { 277 return pipeline().deregister(promise); 278 } 279 280 @Override 281 default ChannelFuture close(ChannelPromise promise) { 282 return pipeline().close(promise); 283 } 284 285 @Override 286 default ChannelFuture disconnect(ChannelPromise promise) { 287 return pipeline().disconnect(promise); 288 } 289 290 @Override 291 default ChannelFuture connect(SocketAddress remoteAddress, SocketAddress localAddress, ChannelPromise promise) { 292 return pipeline().connect(remoteAddress, localAddress, promise); 293 } 294 295 @Override 296 default ChannelFuture connect(SocketAddress remoteAddress, ChannelPromise promise) { 297 return pipeline().connect(remoteAddress, promise); 298 } 299 300 @Override 301 default ChannelFuture bind(SocketAddress localAddress, ChannelPromise promise) { 302 return pipeline().bind(localAddress, promise); 303 } 304 305 @Override 306 default ChannelFuture deregister() { 307 return pipeline().deregister(); 308 } 309 310 @Override 311 default ChannelFuture close() { 312 return pipeline().close(); 313 } 314 315 @Override 316 default ChannelFuture disconnect() { 317 return pipeline().disconnect(); 318 } 319 320 @Override 321 default ChannelFuture connect(SocketAddress remoteAddress, SocketAddress localAddress) { 322 return pipeline().connect(remoteAddress, localAddress); 323 } 324 325 @Override 326 default ChannelFuture connect(SocketAddress remoteAddress) { 327 return pipeline().connect(remoteAddress); 328 } 329 330 @Override 331 default ChannelFuture bind(SocketAddress localAddress) { 332 return pipeline().bind(localAddress); 333 } 334 335 @Override 336 default ChannelPromise newPromise() { 337 return pipeline().newPromise(); 338 } 339 340 @Override 341 default ChannelProgressivePromise newProgressivePromise() { 342 return pipeline().newProgressivePromise(); 343 } 344 345 @Override 346 default ChannelFuture newSucceededFuture() { 347 return pipeline().newSucceededFuture(); 348 } 349 350 @Override 351 default ChannelFuture newFailedFuture(Throwable cause) { 352 return pipeline().newFailedFuture(cause); 353 } 354 355 @Override 356 default ChannelPromise voidPromise() { 357 return pipeline().voidPromise(); 358 } 359 360 /** 361 * <em>Unsafe</em> operations that should <em>never</em> be called from user-code. These methods 362 * are only provided to implement the actual transport, and must be invoked from an I/O thread except for the 363 * following methods: 364 * <ul> 365 * <li>{@link #localAddress()}</li> 366 * <li>{@link #remoteAddress()}</li> 367 * <li>{@link #closeForcibly()}</li> 368 * <li>{@link #register(EventLoop, ChannelPromise)}</li> 369 * <li>{@link #deregister(ChannelPromise)}</li> 370 * <li>{@link #voidPromise()}</li> 371 * </ul> 372 */ 373 interface Unsafe { 374 375 /** 376 * Return the assigned {@link RecvByteBufAllocator.Handle} which will be used to allocate {@link ByteBuf}'s when 377 * receiving data. 378 */ 379 RecvByteBufAllocator.Handle recvBufAllocHandle(); 380 381 /** 382 * Return the {@link SocketAddress} to which is bound local or 383 * {@code null} if none. 384 */ 385 SocketAddress localAddress(); 386 387 /** 388 * Return the {@link SocketAddress} to which is bound remote or 389 * {@code null} if none is bound yet. 390 */ 391 SocketAddress remoteAddress(); 392 393 /** 394 * Register the {@link Channel} of the {@link ChannelPromise} and notify 395 * the {@link ChannelFuture} once the registration was complete. 396 */ 397 void register(EventLoop eventLoop, ChannelPromise promise); 398 399 /** 400 * Bind the {@link SocketAddress} to the {@link Channel} of the {@link ChannelPromise} and notify 401 * it once its done. 402 */ 403 void bind(SocketAddress localAddress, ChannelPromise promise); 404 405 /** 406 * Connect the {@link Channel} of the given {@link ChannelFuture} with the given remote {@link SocketAddress}. 407 * If a specific local {@link SocketAddress} should be used it need to be given as argument. Otherwise just 408 * pass {@code null} to it. 409 * 410 * The {@link ChannelPromise} will get notified once the connect operation was complete. 411 */ 412 void connect(SocketAddress remoteAddress, SocketAddress localAddress, ChannelPromise promise); 413 414 /** 415 * Disconnect the {@link Channel} of the {@link ChannelFuture} and notify the {@link ChannelPromise} once the 416 * operation was complete. 417 */ 418 void disconnect(ChannelPromise promise); 419 420 /** 421 * Close the {@link Channel} of the {@link ChannelPromise} and notify the {@link ChannelPromise} once the 422 * operation was complete. 423 */ 424 void close(ChannelPromise promise); 425 426 /** 427 * Closes the {@link Channel} immediately without firing any events. Probably only useful 428 * when registration attempt failed. 429 */ 430 void closeForcibly(); 431 432 /** 433 * Deregister the {@link Channel} of the {@link ChannelPromise} from {@link EventLoop} and notify the 434 * {@link ChannelPromise} once the operation was complete. 435 */ 436 void deregister(ChannelPromise promise); 437 438 /** 439 * Schedules a read operation that fills the inbound buffer of the first {@link ChannelInboundHandler} in the 440 * {@link ChannelPipeline}. If there's already a pending read operation, this method does nothing. 441 */ 442 void beginRead(); 443 444 /** 445 * Schedules a write operation. 446 */ 447 void write(Object msg, ChannelPromise promise); 448 449 /** 450 * Flush out all write operations scheduled via {@link #write(Object, ChannelPromise)}. 451 */ 452 void flush(); 453 454 /** 455 * Return a special ChannelPromise which can be reused and passed to the operations in {@link Unsafe}. 456 * It will never be notified of a success or error and so is only a placeholder for operations 457 * that take a {@link ChannelPromise} as argument but for which you not want to get notified. 458 */ 459 ChannelPromise voidPromise(); 460 461 /** 462 * Returns the {@link ChannelOutboundBuffer} of the {@link Channel} where the pending write requests are stored. 463 */ 464 ChannelOutboundBuffer outboundBuffer(); 465 } 466 }