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.udt.nio;
17  
18  import com.barchart.udt.TypeUDT;
19  import com.barchart.udt.nio.SocketChannelUDT;
20  import io.netty.buffer.ByteBuf;
21  import io.netty.channel.Channel;
22  import io.netty.channel.ChannelException;
23  import io.netty.channel.ChannelMetadata;
24  import io.netty.channel.FileRegion;
25  import io.netty.channel.nio.AbstractNioByteChannel;
26  import io.netty.channel.udt.DefaultUdtChannelConfig;
27  import io.netty.channel.udt.UdtChannel;
28  import io.netty.channel.udt.UdtChannelConfig;
29  import io.netty.util.internal.logging.InternalLogger;
30  import io.netty.util.internal.logging.InternalLoggerFactory;
31  
32  import java.net.InetSocketAddress;
33  import java.net.SocketAddress;
34  
35  import static java.nio.channels.SelectionKey.*;
36  
37  /**
38   * Byte Channel Connector for UDT Streams.
39   */
40  public class NioUdtByteConnectorChannel extends AbstractNioByteChannel implements UdtChannel {
41  
42      private static final InternalLogger logger =
43              InternalLoggerFactory.getInstance(NioUdtByteConnectorChannel.class);
44  
45      private static final ChannelMetadata METADATA = new ChannelMetadata(false);
46  
47      private final UdtChannelConfig config;
48  
49      public NioUdtByteConnectorChannel() {
50          this(TypeUDT.STREAM);
51      }
52  
53      public NioUdtByteConnectorChannel(final Channel parent, final SocketChannelUDT channelUDT) {
54          super(parent, channelUDT);
55          try {
56              channelUDT.configureBlocking(false);
57              switch (channelUDT.socketUDT().status()) {
58              case INIT:
59              case OPENED:
60                  config = new DefaultUdtChannelConfig(this, channelUDT, true);
61                  break;
62              default:
63                  config = new DefaultUdtChannelConfig(this, channelUDT, false);
64                  break;
65              }
66          } catch (final Exception e) {
67              try {
68                  channelUDT.close();
69              } catch (final Exception e2) {
70                  if (logger.isWarnEnabled()) {
71                      logger.warn("Failed to close channel.", e2);
72                  }
73              }
74              throw new ChannelException("Failed to configure channel.", e);
75          }
76      }
77  
78      public NioUdtByteConnectorChannel(final SocketChannelUDT channelUDT) {
79          this(null, channelUDT);
80      }
81  
82      public NioUdtByteConnectorChannel(final TypeUDT type) {
83          this(NioUdtProvider.newConnectorChannelUDT(type));
84      }
85  
86      @Override
87      public UdtChannelConfig config() {
88          return config;
89      }
90  
91      @Override
92      protected void doBind(final SocketAddress localAddress) throws Exception {
93          javaChannel().bind(localAddress);
94      }
95  
96      @Override
97      protected void doClose() throws Exception {
98          javaChannel().close();
99      }
100 
101     @Override
102     protected boolean doConnect(final SocketAddress remoteAddress,
103             final SocketAddress localAddress) throws Exception {
104         doBind(localAddress != null? localAddress : new InetSocketAddress(0));
105         boolean success = false;
106         try {
107             final boolean connected = javaChannel().connect(remoteAddress);
108             if (!connected) {
109                 selectionKey().interestOps(
110                         selectionKey().interestOps() | OP_CONNECT);
111             }
112             success = true;
113             return connected;
114         } finally {
115             if (!success) {
116                 doClose();
117             }
118         }
119     }
120 
121     @Override
122     protected void doDisconnect() throws Exception {
123         doClose();
124     }
125 
126     @Override
127     protected void doFinishConnect() throws Exception {
128         if (javaChannel().finishConnect()) {
129             selectionKey().interestOps(
130                     selectionKey().interestOps() & ~OP_CONNECT);
131         } else {
132             throw new Error(
133                     "Provider error: failed to finish connect. Provider library should be upgraded.");
134         }
135     }
136 
137     @Override
138     protected int doReadBytes(final ByteBuf byteBuf) throws Exception {
139         return byteBuf.writeBytes(javaChannel(), byteBuf.writableBytes());
140     }
141 
142     @Override
143     protected int doWriteBytes(final ByteBuf byteBuf) throws Exception {
144         final int expectedWrittenBytes = byteBuf.readableBytes();
145         return byteBuf.readBytes(javaChannel(), expectedWrittenBytes);
146     }
147 
148     @Override
149     protected long doWriteFileRegion(FileRegion region) throws Exception {
150         throw new UnsupportedOperationException();
151     }
152 
153     @Override
154     public boolean isActive() {
155         final SocketChannelUDT channelUDT = javaChannel();
156         return channelUDT.isOpen() && channelUDT.isConnectFinished();
157     }
158 
159     @Override
160     protected SocketChannelUDT javaChannel() {
161         return (SocketChannelUDT) super.javaChannel();
162     }
163 
164     @Override
165     protected SocketAddress localAddress0() {
166         return javaChannel().socket().getLocalSocketAddress();
167     }
168 
169     @Override
170     public ChannelMetadata metadata() {
171         return METADATA;
172     }
173 
174     @Override
175     protected SocketAddress remoteAddress0() {
176         return javaChannel().socket().getRemoteSocketAddress();
177     }
178 
179     @Override
180     public InetSocketAddress localAddress() {
181         return (InetSocketAddress) super.localAddress();
182     }
183 
184     @Override
185     public InetSocketAddress remoteAddress() {
186         return (InetSocketAddress) super.remoteAddress();
187     }
188 }