Search in sources :

Example 41 with ChannelFuture

use of org.jboss.netty.channel.ChannelFuture in project socket.io-netty by ibdknox.

the class PollingIOClient method _write.

private void _write(String message) {
    if (!this.open)
        return;
    HttpResponse res = new DefaultHttpResponse(HTTP_1_1, HttpResponseStatus.OK);
    res.addHeader(CONTENT_TYPE, "text/plain; charset=UTF-8");
    res.addHeader("Access-Control-Allow-Origin", "*");
    res.addHeader("Access-Control-Allow-Credentials", "true");
    res.addHeader("Connection", "keep-alive");
    res.setContent(ChannelBuffers.copiedBuffer(message, CharsetUtil.UTF_8));
    setContentLength(res, res.getContent().readableBytes());
    // Send the response and close the connection if necessary.
    Channel chan = ctx.getChannel();
    if (chan.isOpen()) {
        ChannelFuture f = chan.write(res);
        if (!isKeepAlive(req) || res.getStatus().getCode() != 200) {
            f.addListener(ChannelFutureListener.CLOSE);
        }
    }
    this.connected = false;
}
Also used : ChannelFuture(org.jboss.netty.channel.ChannelFuture) DefaultHttpResponse(org.jboss.netty.handler.codec.http.DefaultHttpResponse) Channel(org.jboss.netty.channel.Channel) DefaultHttpResponse(org.jboss.netty.handler.codec.http.DefaultHttpResponse) HttpResponse(org.jboss.netty.handler.codec.http.HttpResponse)

Example 42 with ChannelFuture

use of org.jboss.netty.channel.ChannelFuture in project socket.io-netty by ibdknox.

the class WebSocketServerHandler method sendHttpResponse.

private void sendHttpResponse(ChannelHandlerContext ctx, HttpRequest req, HttpResponse res) {
    // Generate an error page if response status code is not OK (200).
    if (res.getStatus().getCode() != 200) {
        res.setContent(ChannelBuffers.copiedBuffer(res.getStatus().toString(), CharsetUtil.UTF_8));
        setContentLength(res, res.getContent().readableBytes());
    }
    // Send the response and close the connection if necessary.
    ChannelFuture f = ctx.getChannel().write(res);
    if (!isKeepAlive(req) || res.getStatus().getCode() != 200) {
        f.addListener(ChannelFutureListener.CLOSE);
    }
}
Also used : ChannelFuture(org.jboss.netty.channel.ChannelFuture)

Example 43 with ChannelFuture

use of org.jboss.netty.channel.ChannelFuture in project socket.io-netty by ibdknox.

the class FlashPolicyServerHandler method messageReceived.

@Override
public void messageReceived(ChannelHandlerContext ctx, MessageEvent e) throws Exception {
    Object msg = e.getMessage();
    ChannelFuture f = e.getChannel().write(this.getPolicyFileContents());
    f.addListener(ChannelFutureListener.CLOSE);
}
Also used : ChannelFuture(org.jboss.netty.channel.ChannelFuture)

Example 44 with ChannelFuture

use of org.jboss.netty.channel.ChannelFuture in project motan by weibocom.

the class NettyChannel method open.

@Override
public boolean open() {
    if (isAvailable()) {
        LoggerUtil.warn("the channel already open, local: " + localAddress + " remote: " + remoteAddress + " url: " + nettyClient.getUrl().getUri());
        return true;
    }
    ChannelFuture channelFuture = null;
    try {
        synchronized (this) {
            channelFuture = nettyClient.getBootstrap().connect(new InetSocketAddress(nettyClient.getUrl().getHost(), nettyClient.getUrl().getPort()));
            long start = System.currentTimeMillis();
            int timeout = nettyClient.getUrl().getIntParameter(URLParamType.connectTimeout.getName(), URLParamType.connectTimeout.getIntValue());
            if (timeout <= 0) {
                throw new MotanFrameworkException("NettyClient init Error: timeout(" + timeout + ") <= 0 is forbid.", MotanErrorMsgConstant.FRAMEWORK_INIT_ERROR);
            }
            // 不去依赖于connectTimeout
            boolean result = channelFuture.awaitUninterruptibly(timeout, TimeUnit.MILLISECONDS);
            boolean success = channelFuture.isSuccess();
            if (result && success) {
                channel = channelFuture.getChannel();
                if (channel.getLocalAddress() != null && channel.getLocalAddress() instanceof InetSocketAddress) {
                    localAddress = (InetSocketAddress) channel.getLocalAddress();
                }
                state = ChannelState.ALIVE;
                return true;
            }
            boolean connected = false;
            if (channelFuture.getChannel() != null) {
                connected = channelFuture.getChannel().isConnected();
            }
            if (channelFuture.getCause() != null) {
                channelFuture.cancel();
                throw new MotanServiceException("NettyChannel failed to connect to server, url: " + nettyClient.getUrl().getUri() + ", result: " + result + ", success: " + success + ", connected: " + connected, channelFuture.getCause());
            } else {
                channelFuture.cancel();
                throw new MotanServiceException("NettyChannel connect to server timeout url: " + nettyClient.getUrl().getUri() + ", cost: " + (System.currentTimeMillis() - start) + ", result: " + result + ", success: " + success + ", connected: " + connected, false);
            }
        }
    } catch (MotanServiceException e) {
        throw e;
    } catch (Exception e) {
        if (channelFuture != null) {
            channelFuture.getChannel().close();
        }
        throw new MotanServiceException("NettyChannel failed to connect to server, url: " + nettyClient.getUrl().getUri(), e);
    } finally {
        if (!state.isAliveState()) {
            // 为避免死锁,client错误计数方法需在同步块外调用。
            nettyClient.incrErrorCount();
        }
    }
}
Also used : ChannelFuture(org.jboss.netty.channel.ChannelFuture) MotanFrameworkException(com.weibo.api.motan.exception.MotanFrameworkException) InetSocketAddress(java.net.InetSocketAddress) MotanServiceException(com.weibo.api.motan.exception.MotanServiceException) MotanServiceException(com.weibo.api.motan.exception.MotanServiceException) MotanFrameworkException(com.weibo.api.motan.exception.MotanFrameworkException) TransportException(com.weibo.api.motan.transport.TransportException)

Example 45 with ChannelFuture

use of org.jboss.netty.channel.ChannelFuture in project motan by weibocom.

the class NettyChannel method request.

@Override
public Response request(Request request) throws TransportException {
    int timeout = nettyClient.getUrl().getMethodParameter(request.getMethodName(), request.getParamtersDesc(), URLParamType.requestTimeout.getName(), URLParamType.requestTimeout.getIntValue());
    if (timeout <= 0) {
        throw new MotanFrameworkException("NettyClient init Error: timeout(" + timeout + ") <= 0 is forbid.", MotanErrorMsgConstant.FRAMEWORK_INIT_ERROR);
    }
    ResponseFuture response = new DefaultResponseFuture(request, timeout, this.nettyClient.getUrl());
    this.nettyClient.registerCallback(request.getRequestId(), response);
    ChannelFuture writeFuture = this.channel.write(request);
    boolean result = writeFuture.awaitUninterruptibly(timeout, TimeUnit.MILLISECONDS);
    if (result && writeFuture.isSuccess()) {
        MotanFrameworkUtil.logEvent(request, MotanConstants.TRACE_CSEND, System.currentTimeMillis());
        response.addListener(new FutureListener() {

            @Override
            public void operationComplete(Future future) throws Exception {
                if (future.isSuccess() || (future.isDone() && ExceptionUtil.isBizException(future.getException()))) {
                    // 成功的调用
                    nettyClient.resetErrorCount();
                } else {
                    // 失败的调用
                    nettyClient.incrErrorCount();
                }
            }
        });
        return response;
    }
    writeFuture.cancel();
    response = this.nettyClient.removeCallback(request.getRequestId());
    if (response != null) {
        response.cancel();
    }
    // 失败的调用
    nettyClient.incrErrorCount();
    if (writeFuture.getCause() != null) {
        throw new MotanServiceException("NettyChannel send request to server Error: url=" + nettyClient.getUrl().getUri() + " local=" + localAddress + " " + MotanFrameworkUtil.toString(request), writeFuture.getCause());
    } else {
        throw new MotanServiceException("NettyChannel send request to server Timeout: url=" + nettyClient.getUrl().getUri() + " local=" + localAddress + " " + MotanFrameworkUtil.toString(request), false);
    }
}
Also used : ChannelFuture(org.jboss.netty.channel.ChannelFuture) MotanFrameworkException(com.weibo.api.motan.exception.MotanFrameworkException) ChannelFuture(org.jboss.netty.channel.ChannelFuture) MotanServiceException(com.weibo.api.motan.exception.MotanServiceException) MotanServiceException(com.weibo.api.motan.exception.MotanServiceException) MotanFrameworkException(com.weibo.api.motan.exception.MotanFrameworkException) TransportException(com.weibo.api.motan.transport.TransportException)

Aggregations

ChannelFuture (org.jboss.netty.channel.ChannelFuture)138 Channel (org.jboss.netty.channel.Channel)40 DefaultHttpResponse (org.jboss.netty.handler.codec.http.DefaultHttpResponse)38 HttpResponse (org.jboss.netty.handler.codec.http.HttpResponse)28 ChannelBuffer (org.jboss.netty.buffer.ChannelBuffer)27 HttpRequest (org.jboss.netty.handler.codec.http.HttpRequest)26 InetSocketAddress (java.net.InetSocketAddress)25 ChannelFutureListener (org.jboss.netty.channel.ChannelFutureListener)23 DefaultHttpRequest (org.jboss.netty.handler.codec.http.DefaultHttpRequest)23 Test (org.junit.Test)15 SucceededChannelFuture (org.jboss.netty.channel.SucceededChannelFuture)13 ClientBootstrap (org.jboss.netty.bootstrap.ClientBootstrap)12 InvocationOnMock (org.mockito.invocation.InvocationOnMock)12 PrepareForTest (org.powermock.core.classloader.annotations.PrepareForTest)10 NioClientSocketChannelFactory (org.jboss.netty.channel.socket.nio.NioClientSocketChannelFactory)9 Test (org.testng.annotations.Test)8 IOException (java.io.IOException)7 ConnectException (java.net.ConnectException)7 ArrayList (java.util.ArrayList)7 HashMap (java.util.HashMap)6