Search in sources :

Example 1 with HttpFrame

use of com.firenio.codec.http11.HttpFrame in project baseio by generallycloud.

the class TestHttpLoadServerTFB method main.

public static void main(String[] args) throws Exception {
    System.setProperty("core", "1");
    System.setProperty("frame", "16");
    System.setProperty("readBuf", "512");
    System.setProperty("pool", "true");
    System.setProperty("inline", "true");
    System.setProperty("level", "1");
    System.setProperty("read", "false");
    System.setProperty("epoll", "true");
    System.setProperty("nodelay", "true");
    System.setProperty("cachedurl", "true");
    System.setProperty("unsafeBuf", "false");
    boolean lite = Util.getBooleanProperty("lite");
    boolean read = Util.getBooleanProperty("read");
    boolean pool = Util.getBooleanProperty("pool");
    boolean epoll = Util.getBooleanProperty("epoll");
    boolean direct = Util.getBooleanProperty("direct");
    boolean nodelay = Util.getBooleanProperty("nodelay");
    boolean cachedurl = Util.getBooleanProperty("cachedurl");
    boolean unsafeBuf = Util.getBooleanProperty("unsafeBuf");
    int core = Util.getIntProperty("core", 1);
    int frame = Util.getIntProperty("frame", 16);
    int level = Util.getIntProperty("level", 1);
    int readBuf = Util.getIntProperty("readBuf", 16);
    LoggerFactory.setEnableSLF4JLogger(false);
    LoggerFactory.setLogLevel(LoggerFactory.LEVEL_INFO);
    Options.setBufAutoExpansion(false);
    Options.setChannelReadFirst(read);
    Options.setEnableEpoll(epoll);
    Options.setEnableUnsafeBuf(unsafeBuf);
    DebugUtil.info("lite: {}", lite);
    DebugUtil.info("read: {}", read);
    DebugUtil.info("pool: {}", pool);
    DebugUtil.info("core: {}", core);
    DebugUtil.info("epoll: {}", epoll);
    DebugUtil.info("frame: {}", frame);
    DebugUtil.info("level: {}", level);
    DebugUtil.info("readBuf: {}", readBuf);
    DebugUtil.info("nodelay: {}", nodelay);
    DebugUtil.info("cachedurl: {}", cachedurl);
    DebugUtil.info("unsafeBuf: {}", unsafeBuf);
    int processors = Util.availableProcessors() * core;
    int fcache = 1024 * 16;
    int pool_unit = 256 * 16;
    int pool_cap = 1024 * 8 * pool_unit * processors;
    String server = "firenio";
    ByteTree cachedUrls = null;
    if (cachedurl) {
        cachedUrls = new ByteTree();
        cachedUrls.add("/plaintext");
        cachedUrls.add("/json");
    }
    HttpCodec codec = new HttpCodec(server, fcache, lite, cachedUrls) {

        @Override
        protected Object newAttachment() {
            return new MyHttpAttachment();
        }
    };
    IoEventHandle eventHandle = new IoEventHandle() {

        @Override
        public void accept(Channel ch, Frame frame) throws Exception {
            HttpFrame f = (HttpFrame) frame;
            String action = f.getRequestURL();
            if ("/plaintext".equals(action)) {
                MyHttpAttachment att = (MyHttpAttachment) ch.getAttachment();
                ByteBuf buf = att.write_buf;
                if (buf == null) {
                    buf = ch.allocate();
                    ByteBuf temp = buf;
                    att.write_buf = buf;
                    ch.getEventLoop().submit(() -> {
                        ch.writeAndFlush(temp);
                        att.write_buf = null;
                    });
                }
                f.setContent(STATIC_PLAINTEXT);
                f.setContentType(HttpContentType.text_plain);
                f.setConnection(HttpConnection.NONE);
                f.setDate(HttpDateUtil.getDateLine());
                codec.encode(ch, buf, f);
                codec.release(ch.getEventLoop(), f);
            } else if ("/json".equals(action)) {
                ByteBuf temp = FastThreadLocal.get().getAttribute(JSON_BUF);
                if (temp == null) {
                    temp = ByteBuf.heap(0);
                    FastThreadLocal.get().setAttribute(JSON_BUF, temp);
                }
                JsonStream stream = JsonStreamPool.borrowJsonStream();
                try {
                    stream.reset(null);
                    stream.writeVal(Message.class, new Message("Hello, World!"));
                    Slice slice = stream.buffer();
                    temp.reset(slice.data(), slice.head(), slice.tail());
                    f.setContent(temp);
                    f.setContentType(HttpContentType.application_json);
                    f.setConnection(HttpConnection.NONE);
                    f.setDate(HttpDateUtil.getDateLine());
                    ch.writeAndFlush(f);
                    ch.release(f);
                } finally {
                    JsonStreamPool.returnJsonStream(stream);
                }
            } else {
                System.err.println("404");
                f.setString("404,page not found!", ch);
                f.setContentType(HttpContentType.text_plain);
                f.setStatus(HttpStatus.C404);
                f.setDate(HttpDateUtil.getDateLine());
                ch.writeAndFlush(f);
                ch.release(f);
            }
        }
    };
    HttpDateUtil.start();
    NioEventLoopGroup group = new NioEventLoopGroup();
    ChannelAcceptor context = new ChannelAcceptor(group, 8081);
    group.setMemoryCapacity(pool_cap);
    group.setEnableMemoryPool(pool);
    group.setMemoryUnit(pool_unit);
    group.setWriteBuffers(8);
    group.setChannelReadBuffer(1024 * readBuf);
    group.setEventLoopSize(Util.availableProcessors() * core);
    group.setConcurrentFrameStack(false);
    if (nodelay) {
        context.addChannelEventListener(new ChannelEventListenerAdapter() {

            @Override
            public void channelOpened(Channel ch) throws Exception {
                ch.setOption(SocketOptions.TCP_NODELAY, 1);
                ch.setOption(SocketOptions.SO_KEEPALIVE, 0);
            }
        });
    }
    context.addProtocolCodec(codec);
    context.setIoEventHandle(eventHandle);
    context.bind(1024 * 8);
}
Also used : IoEventHandle(com.firenio.component.IoEventHandle) Frame(com.firenio.component.Frame) HttpFrame(com.firenio.codec.http11.HttpFrame) Channel(com.firenio.component.Channel) ChannelAcceptor(com.firenio.component.ChannelAcceptor) JsonStream(com.jsoniter.output.JsonStream) ByteBuf(com.firenio.buffer.ByteBuf) HttpFrame(com.firenio.codec.http11.HttpFrame) ChannelEventListenerAdapter(com.firenio.component.ChannelEventListenerAdapter) ByteTree(com.firenio.collection.ByteTree) HttpCodec(com.firenio.codec.http11.HttpCodec) Slice(com.jsoniter.spi.Slice) NioEventLoopGroup(com.firenio.component.NioEventLoopGroup)

Example 2 with HttpFrame

use of com.firenio.codec.http11.HttpFrame in project baseio by generallycloud.

the class TestWebSocketRumpetrollServlet method accept.

@Override
public void accept(Channel ch, Frame frame) throws Exception {
    if (frame instanceof HttpFrame) {
        HttpFrame f = (HttpFrame) frame;
        f.updateWebSocketProtocol(ch);
        msgAdapter.addClient(ch.getDesc(), ch);
        JSONObject o = new JSONObject();
        o.put("type", "welcome");
        o.put("id", ch.getChannelId());
        WebSocketFrame wsf = new WebSocketFrame();
        wsf.setString(o.toJSONString(), ch);
        ch.writeAndFlush(wsf);
        return;
    }
    WebSocketFrame f = (WebSocketFrame) frame;
    // CLOSE
    if (f.isCloseFrame()) {
        if (msgAdapter.removeClient(ch) != null) {
            JSONObject o = new JSONObject();
            o.put("type", "closed");
            o.put("id", ch.getChannelId());
            msgAdapter.sendMsg(o.toJSONString());
            logger.info("客户端主动关闭连接:{}", ch);
        }
        ch.close();
    } else {
        String msg = f.getStringContent();
        JSONObject o = JSON.parseObject(msg);
        String name = o.getString("name");
        if (Util.isNullOrBlank(name)) {
            name = Util.randomUUID();
        }
        o.put("name", name);
        o.put("id", ch.getChannelId());
        String type = o.getString("type");
        if ("update".equals(type)) {
            o.put("life", "1");
            o.put("authorized", "false");
            o.put("x", Double.valueOf(o.getString("x")));
            o.put("y", Double.valueOf(o.getString("x")));
            o.put("momentum", Double.valueOf(o.getString("momentum")));
            o.put("angle", Double.valueOf(o.getString("angle")));
        } else if ("message".equals(type)) {
        }
        msgAdapter.sendMsg(o.toJSONString());
    }
}
Also used : JSONObject(com.alibaba.fastjson.JSONObject) WebSocketFrame(com.firenio.codec.http11.WebSocketFrame) HttpFrame(com.firenio.codec.http11.HttpFrame)

Example 3 with HttpFrame

use of com.firenio.codec.http11.HttpFrame in project baseio by generallycloud.

the class HttpFrameHandle method printHtml.

protected void printHtml(Channel ch, Frame frame, HttpStatus status, String content) throws Exception {
    HttpFrame f = (HttpFrame) frame;
    StringBuilder builder = new StringBuilder(HttpUtil.HTML_HEADER);
    builder.append("        <div style=\"margin-left:20px;\">\n");
    builder.append("            ");
    builder.append(content);
    builder.append("            </div>\n");
    builder.append("        </div>\n");
    builder.append(HttpUtil.HTML_POWER_BY);
    builder.append(HttpUtil.HTML_BOTTOM);
    byte[] data = builder.toString().getBytes(ch.getCharset());
    f.setContent(data);
    f.setStatus(status);
    f.setContentType(HttpContentType.text_html_utf8);
    ch.writeAndFlush(f);
}
Also used : HttpFrame(com.firenio.codec.http11.HttpFrame)

Example 4 with HttpFrame

use of com.firenio.codec.http11.HttpFrame in project baseio by generallycloud.

the class HttpFrameHandle method acceptHtml.

protected void acceptHtml(Channel ch, Frame frame) throws Exception {
    String frameName = HttpUtil.getFrameName(ch, frame);
    HttpEntity entity = null;
    if (frameName.equals("/")) {
        entity = htmlCache.get(welcome);
    }
    if (entity == null) {
        entity = htmlCache.get(frameName);
    }
    HttpStatus status = HttpStatus.C200;
    HttpFrame f = (HttpFrame) frame;
    if (entity == null) {
        entity = htmlCache.get("/404.html");
        if (entity == null) {
            printHtml(ch, frame, HttpStatus.C404, "404 page not found");
            return;
        }
    }
    File file = entity.getFile();
    if (file != null && file.lastModified() > entity.getLastModify()) {
        synchronized (entity) {
            if (file.lastModified() > entity.getLastModify()) {
                reloadEntity(entity, ch.getContext(), status);
            }
        }
        writeAndFlush(ch, f, entity);
        return;
    }
    String ims = f.getRequestHeader(HttpHeader.If_Modified_Since);
    long imsTime = -1;
    if (!Util.isNullOrBlank(ims)) {
        imsTime = DateUtil.get().parseHttp(ims).getTime();
    }
    if (imsTime < entity.getLastModifyGTMTime()) {
        writeAndFlush(ch, f, entity);
        return;
    }
    f.setStatus(HttpStatus.C304);
    ch.writeAndFlush(f);
}
Also used : HttpStatus(com.firenio.codec.http11.HttpStatus) HttpFrame(com.firenio.codec.http11.HttpFrame) File(java.io.File)

Example 5 with HttpFrame

use of com.firenio.codec.http11.HttpFrame in project baseio by generallycloud.

the class HttpProxyServer method strtup.

public synchronized void strtup(NioEventLoopGroup group, int port) throws Exception {
    if (context != null && context.isActive()) {
        return;
    }
    IoEventHandle eventHandle = new IoEventHandle() {

        @Override
        public void accept(Channel ch_src, Frame frame) throws Exception {
            final HttpFrame f = (HttpFrame) frame;
            if (f.getMethod() == HttpMethod.CONNECT) {
                ch_src.writeAndFlush(CONNECT_RES_BUF.duplicate());
                HttpProxyAttr s = HttpProxyAttr.get(ch_src);
                String[] arr = f.getHost().split(":");
                s.host = arr[0];
                s.port = Integer.parseInt(arr[1]);
                s.handshakeFinished = true;
            } else {
                String host = f.getHost();
                String[] arr = host.split(":");
                int port = 80;
                if (arr.length == 2) {
                    port = Integer.parseInt(arr[1]);
                }
                if (f.getRequestHeaders().remove(HttpHeader.Proxy_Connection.getId()) == null) {
                    return;
                }
                NioEventLoop el = ch_src.getEventLoop();
                ChannelConnector context = new ChannelConnector(el, arr[0], port);
                context.addProtocolCodec(new ClientHttpCodec());
                context.setIoEventHandle(new IoEventHandle() {

                    @Override
                    public void accept(Channel ch, Frame frame) throws Exception {
                        ClientHttpFrame res = (ClientHttpFrame) frame;
                        IntObjectMap<String> hs = res.getResponse_headers();
                        for (hs.scan(); hs.hasNext(); ) {
                            String v = hs.getValue();
                            if (v == null) {
                                continue;
                            }
                            if (hs.getKey() == HttpHeader.Content_Length.getId() || hs.getKey() == HttpHeader.Connection.getId() || hs.getKey() == HttpHeader.Transfer_Encoding.getId() || hs.getKey() == HttpHeader.Content_Encoding.getId()) {
                                continue;
                            }
                            f.setResponseHeader(hs.getKey(), v.getBytes());
                        }
                        if (res.getContent() != null) {
                            f.setContent(res.getContent());
                        } else if (res.isChunked()) {
                            f.setString("not support chunked now.", ch);
                        }
                        ch_src.writeAndFlush(f);
                        ch.close();
                    }
                });
                String url = parseRequestURL(f.getRequestURL());
                context.setPrintConfig(false);
                context.addChannelEventListener(new LoggerChannelOpenListener());
                context.connect((ch, ex) -> {
                    if (ex == null) {
                        ClientHttpFrame req = new ClientHttpFrame(url, f.getMethod());
                        req.setRequestHeaders(f.getRequestHeaders());
                        req.getRequestHeaders().remove(HttpHeader.Proxy_Connection.getId());
                        if (f.getMethod() == HttpMethod.POST) {
                            req.setContent(f.getContent());
                        }
                        try {
                            ch.writeAndFlush(req);
                        } catch (Exception e) {
                            e.printStackTrace();
                        }
                    }
                });
            }
        }
    };
    context = new ChannelAcceptor(group, 8088);
    context.addProtocolCodec(new HttpProxyCodec());
    context.setIoEventHandle(eventHandle);
    context.addChannelEventListener(new LoggerChannelOpenListener());
    context.bind();
}
Also used : IoEventHandle(com.firenio.component.IoEventHandle) Frame(com.firenio.component.Frame) ClientHttpFrame(com.firenio.codec.http11.ClientHttpFrame) HttpFrame(com.firenio.codec.http11.HttpFrame) Channel(com.firenio.component.Channel) ChannelAcceptor(com.firenio.component.ChannelAcceptor) ClientHttpFrame(com.firenio.codec.http11.ClientHttpFrame) HttpFrame(com.firenio.codec.http11.HttpFrame) IOException(java.io.IOException) LoggerChannelOpenListener(com.firenio.component.LoggerChannelOpenListener) IntObjectMap(com.firenio.collection.IntObjectMap) ChannelConnector(com.firenio.component.ChannelConnector) ClientHttpCodec(com.firenio.codec.http11.ClientHttpCodec) NioEventLoop(com.firenio.component.NioEventLoop) ClientHttpFrame(com.firenio.codec.http11.ClientHttpFrame)

Aggregations

HttpFrame (com.firenio.codec.http11.HttpFrame)8 Channel (com.firenio.component.Channel)5 Frame (com.firenio.component.Frame)4 IoEventHandle (com.firenio.component.IoEventHandle)4 WebSocketFrame (com.firenio.codec.http11.WebSocketFrame)3 ChannelAcceptor (com.firenio.component.ChannelAcceptor)3 LoggerChannelOpenListener (com.firenio.component.LoggerChannelOpenListener)3 NioEventLoopGroup (com.firenio.component.NioEventLoopGroup)3 JSONObject (com.alibaba.fastjson.JSONObject)2 ClientHttpCodec (com.firenio.codec.http11.ClientHttpCodec)2 ClientHttpFrame (com.firenio.codec.http11.ClientHttpFrame)2 HttpCodec (com.firenio.codec.http11.HttpCodec)2 WebSocketCodec (com.firenio.codec.http11.WebSocketCodec)2 ChannelConnector (com.firenio.component.ChannelConnector)2 HashMap (java.util.HashMap)2 ByteBuf (com.firenio.buffer.ByteBuf)1 Cookie (com.firenio.codec.http11.Cookie)1 HttpStatus (com.firenio.codec.http11.HttpStatus)1 WsUpgradeRequestFrame (com.firenio.codec.http11.WsUpgradeRequestFrame)1 ByteTree (com.firenio.collection.ByteTree)1