Search in sources :

Example 16 with Channel

use of com.firenio.component.Channel in project baseio by generallycloud.

the class TestShowMemoryServlet method doAccept.

@Override
protected void doAccept(Channel ch, HttpFrame f) throws Exception {
    TestWebSocketChatServlet chatServlet = context.getBean(TestWebSocketChatServlet.class);
    TestWebSocketRumpetrollServlet rumpetrollServlet = context.getBean(TestWebSocketRumpetrollServlet.class);
    WebSocketMsgAdapter chatMsgAdapter = chatServlet.getMsgAdapter();
    WebSocketMsgAdapter rumpetrollMsgAdapter = rumpetrollServlet.getMsgAdapter();
    ChannelContext context = ch.getContext();
    String kill = f.getRequestParam("kill");
    if (!Util.isNullOrBlank(kill)) {
        Integer id = Integer.valueOf(kill, 16);
        Channel close_ch = CountChannelListener.chs.get(id);
        if (close_ch != null) {
            close_ch.getEventLoop().schedule(new DelayTask(10) {

                @Override
                public void run() {
                    Util.close(close_ch);
                }
            });
        }
    }
    BigDecimal time = new BigDecimal(Util.now_f() - context.getStartupTime());
    BigDecimal anHour = new BigDecimal(60 * 60 * 1000);
    BigDecimal hour = time.divide(anHour, 3, RoundingMode.HALF_UP);
    NioEventLoopGroup group = ch.getEventLoop().getGroup();
    ByteBufAllocatorGroup allocator = group.getAllocatorGroup();
    String allocatorDes = "unpooled";
    if (allocator != null) {
        StringBuilder builder = new StringBuilder();
        String[] res = allocator.toDebugString();
        for (int i = 0; i < res.length; i++) {
            builder.append("<BR/>\n");
            builder.append(res[i]);
        }
        allocatorDes = builder.toString();
    }
    int M = 1024 * 1024;
    int eventLoopSize = group.getEventLoopSize();
    int SERVER_MEMORY_POOL_UNIT = group.getMemoryUnit();
    long SERVER_MEMORY_POOL_CAPACITY = group.getMemoryCapacity();
    double MEMORY_POOL_SIZE = SERVER_MEMORY_POOL_CAPACITY / (M * 1d);
    MEMORY_POOL_SIZE = new BigDecimal(MEMORY_POOL_SIZE).setScale(2, BigDecimal.ROUND_HALF_UP).doubleValue();
    Runtime runtime = Runtime.getRuntime();
    StringBuilder builder = new StringBuilder(HttpUtil.HTML_HEADER);
    builder.append("		<div style=\"margin-left:20px;\">\n");
    builder.append("服务器内存使用情况:</BR>\n");
    builder.append("虚拟机占用内存:");
    builder.append(runtime.totalMemory() / M);
    builder.append("M;\n</BR>已占用内存:");
    builder.append((runtime.totalMemory() - runtime.freeMemory()) / M);
    builder.append("M;\n</BR>空闲内存:");
    builder.append(runtime.freeMemory() / M);
    builder.append("M;\n</BR>内存池大小:");
    builder.append(MEMORY_POOL_SIZE);
    builder.append("M;\n</BR>内存池状态:");
    builder.append(allocatorDes);
    builder.append("\n</BR>聊天室(WebSocket)客户端数量:");
    builder.append(chatMsgAdapter.getClientSize());
    builder.append("\n</BR>小蝌蚪(WebSocket)客户端数量:");
    builder.append(rumpetrollMsgAdapter.getClientSize());
    builder.append("\n</BR>服务器当前连接数(io-channel):");
    builder.append(CountChannelListener.chs.size());
    for (Channel s : CountChannelListener.chs.values()) {
        builder.append("\n</BR>");
        builder.append(s);
        builder.append(", opened: ");
        builder.append(DateUtil.get().formatYyyy_MM_dd_HH_mm_ss(new Date(s.getCreationTime())));
    }
    builder.append(";\n</BR>服务运行时间:");
    builder.append(hour + "H;");
    builder.append("		</div>\n");
    builder.append(HttpUtil.HTML_POWER_BY);
    builder.append(HttpUtil.HTML_BOTTOM);
    f.setString(builder.toString(), ch);
    f.setContentType(HttpContentType.text_html_utf8);
    ch.writeAndFlush(f);
}
Also used : ByteBufAllocatorGroup(com.firenio.buffer.ByteBufAllocatorGroup) Channel(com.firenio.component.Channel) BigDecimal(java.math.BigDecimal) Date(java.util.Date) ChannelContext(com.firenio.component.ChannelContext) DelayTask(com.firenio.collection.DelayedQueue.DelayTask) NioEventLoopGroup(com.firenio.component.NioEventLoopGroup)

Example 17 with Channel

use of com.firenio.component.Channel in project baseio by generallycloud.

the class TestSimpleWebSocketClient method main.

public static void main(String[] args) throws Exception {
    IoEventHandle eventHandleAdaptor = new IoEventHandle() {

        @Override
        public void accept(Channel ch, Frame frame) throws Exception {
            if (frame instanceof ClientHttpFrame) {
                ClientHttpFrame f = (ClientHttpFrame) frame;
                if (f.updateWebSocketProtocol(ch)) {
                    WebSocketFrame f2 = new WebSocketFrame();
                    Map<String, String> map = new HashMap<>();
                    map.put("action", "add-user");
                    map.put("username", "火星人" + Util.randomUUID());
                    f2.setString(JSON.toJSONString(map), ch);
                    ch.writeAndFlush(f2);
                }
                System.out.println(f.getResponse_headers());
            } else {
                WebSocketFrame f = (WebSocketFrame) frame;
                System.out.println(f.getStringContent());
            }
        }
    };
    String host = "firenio.com";
    int port = 443;
    NioEventLoopGroup g = new NioEventLoopGroup();
    g.setEnableMemoryPool(false);
    ChannelConnector context = new ChannelConnector(g, host, 443);
    // context.setExecutorGroup(new ExecutorEventLoopGroup());
    context.setIoEventHandle(eventHandleAdaptor);
    context.addProtocolCodec(new ClientHttpCodec());
    context.addProtocolCodec(new WebSocketCodec());
    context.addChannelEventListener(new LoggerChannelOpenListener());
    context.setSslContext(SslContextBuilder.forClient(true).build());
    Channel ch = context.connect();
    String url = "/web-socket-chat";
    HttpFrame frame = new WsUpgradeRequestFrame(url);
    frame.setRequestHeader(HttpHeader.Host, host + port);
    frame.setRequestHeader(HttpHeader.Pragma, "no-cache");
    frame.setRequestHeader(HttpHeader.Cache_Control, "no-cache");
    frame.setRequestHeader(HttpHeader.User_Agent, "Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/53.0.2785.143 Safari/537.36");
    frame.setRequestHeader(HttpHeader.Accept_Encoding, "gzip, deflate, sdch");
    frame.setRequestHeader(HttpHeader.Accept_Language, "zh-CN,zh;q=0.8");
    ch.writeAndFlush(frame);
    Util.sleep(100);
    WebSocketFrame f2 = new WebSocketFrame();
    Map<String, String> map = new HashMap<>();
    map.put("action", "new-message");
    map.put("message", TestUtil.newString(1024 * 8));
    f2.setString(JSON.toJSONString(map), ch);
    ch.writeAndFlush(f2);
    Util.sleep(999999999);
    Util.close(context);
}
Also used : IoEventHandle(com.firenio.component.IoEventHandle) Frame(com.firenio.component.Frame) ClientHttpFrame(com.firenio.codec.http11.ClientHttpFrame) WebSocketFrame(com.firenio.codec.http11.WebSocketFrame) WsUpgradeRequestFrame(com.firenio.codec.http11.WsUpgradeRequestFrame) HttpFrame(com.firenio.codec.http11.HttpFrame) HashMap(java.util.HashMap) Channel(com.firenio.component.Channel) ClientHttpFrame(com.firenio.codec.http11.ClientHttpFrame) HttpFrame(com.firenio.codec.http11.HttpFrame) LoggerChannelOpenListener(com.firenio.component.LoggerChannelOpenListener) WsUpgradeRequestFrame(com.firenio.codec.http11.WsUpgradeRequestFrame) ChannelConnector(com.firenio.component.ChannelConnector) ClientHttpCodec(com.firenio.codec.http11.ClientHttpCodec) WebSocketFrame(com.firenio.codec.http11.WebSocketFrame) ClientHttpFrame(com.firenio.codec.http11.ClientHttpFrame) NioEventLoopGroup(com.firenio.component.NioEventLoopGroup) WebSocketCodec(com.firenio.codec.http11.WebSocketCodec)

Example 18 with Channel

use of com.firenio.component.Channel in project baseio by generallycloud.

the class HttpProxy4CloudServer method strtup.

public synchronized void strtup(NioEventLoopGroup serverG, int port) throws Exception {
    if (context != null && context.isActive()) {
        return;
    }
    context = new ChannelAcceptor(serverG, 8088);
    context.addProtocolCodec(new HttpProxy4CloudCodec());
    context.addChannelEventListener(new LoggerChannelOpenListener());
    context.addChannelEventListener(new ChannelEventListenerAdapter() {

        @Override
        public void channelClosed(Channel ch) {
            Util.close(((HttpProxy4CloudAttr) ch.getAttachment()).target);
        }
    });
    context.bind();
}
Also used : Channel(com.firenio.component.Channel) ChannelAcceptor(com.firenio.component.ChannelAcceptor) ChannelEventListenerAdapter(com.firenio.component.ChannelEventListenerAdapter) LoggerChannelOpenListener(com.firenio.component.LoggerChannelOpenListener)

Example 19 with Channel

use of com.firenio.component.Channel in project baseio by generallycloud.

the class TestWebSocketChatServlet method accept.

@Override
public void accept(Channel ch, Frame frame) throws Exception {
    if (frame instanceof HttpFrame) {
        ((HttpFrame) frame).updateWebSocketProtocol(ch);
        return;
    }
    WebSocketFrame f = (WebSocketFrame) frame;
    // CLOSE
    if (f.isCloseFrame()) {
        Client client = msgAdapter.removeClient(ch);
        if (client != null) {
            JSONObject obj = new JSONObject();
            obj.put("username", client.getUsername());
            obj.put("numUsers", msgAdapter.getClientSize());
            obj.put("action", "user-left");
            String msg1 = obj.toJSONString();
            msgAdapter.sendMsg(msg1);
        }
        ch.close();
    } else {
        String msg = f.getStringContent();
        JSONObject obj = JSON.parseObject(msg);
        String action = obj.getString("action");
        if ("add-user".equals(action)) {
            String username = obj.getString("username");
            if (Util.isNullOrBlank(username)) {
                return;
            }
            msgAdapter.addClient(username, ch);
            obj.put("numUsers", msgAdapter.getClientSize());
            obj.put("action", "login");
            msgAdapter.sendMsg(ch, obj.toJSONString());
            obj.put("username", username);
            obj.put("action", "user-joined");
            msgAdapter.sendMsg(obj.toJSONString());
            obj.put("action", "new-message");
            obj.put("username", "系统消息");
            obj.put("message", "欢迎加入QQ群讨论java io相关技术:540637859,@某人可以单独向他发送消息。");
            msgAdapter.sendMsg(ch, obj.toJSONString());
            return;
        }
        Client client = msgAdapter.getClient(ch.getChannelId());
        if (client == null) {
            return;
        }
        String username = client.getUsername();
        if ("new-message".equals(action)) {
            String message = obj.getString("message");
            if (message.charAt(0) == '@') {
                int nIndex = message.indexOf(' ');
                if (nIndex > 1) {
                    String to_username = message.substring(1, nIndex);
                    Channel s = msgAdapter.getChannel(to_username);
                    if (s == null) {
                        obj.put("message", "用户不存在或者已离线");
                        obj.put("username", username);
                        msgAdapter.sendMsg(ch, obj.toJSONString());
                        return;
                    }
                    obj.put("username", username);
                    msgAdapter.sendMsg(ch, obj.toJSONString());
                    obj.put("username", username + "@你");
                    obj.put("message", message.substring(nIndex));
                    msgAdapter.sendMsg(s, obj.toJSONString());
                    return;
                }
            }
            obj.put("username", username);
            String msg1 = obj.toJSONString();
            msgAdapter.sendMsg(msg1);
        } else if ("typing".equals(action)) {
            obj.put("username", username);
            String msg1 = obj.toJSONString();
            msgAdapter.sendMsg(msg1);
        } else if ("stop-typing".equals(action)) {
            obj.put("username", username);
            String msg1 = obj.toJSONString();
            msgAdapter.sendMsg(msg1);
        } else if ("disconnect".equals(action)) {
            msgAdapter.removeClient(ch);
            obj.put("username", username);
            obj.put("numUsers", msgAdapter.getClientSize());
            obj.put("action", "user-left");
            String msg1 = obj.toJSONString();
            msgAdapter.sendMsg(msg1);
        } else {
            f.write("no action matched:" + action, ch);
            ch.writeAndFlush(f);
        }
    }
}
Also used : JSONObject(com.alibaba.fastjson.JSONObject) Channel(com.firenio.component.Channel) WebSocketFrame(com.firenio.codec.http11.WebSocketFrame) Client(sample.http11.service.WebSocketMsgAdapter.Client) HttpFrame(com.firenio.codec.http11.HttpFrame)

Example 20 with Channel

use of com.firenio.component.Channel in project baseio by generallycloud.

the class TestByteBufPool method main.

public static void main(String[] args) throws Exception {
    ChannelConnector context = new ChannelConnector("192.168.1.102", 6500);
    context.addChannelEventListener(new LoggerChannelOpenListener());
    context.addProtocolCodec(new LengthValueCodec());
    Channel ch = context.connect(3000);
    ByteBuf buf = ch.allocate();
    ch.close();
    buf.release();
}
Also used : LengthValueCodec(com.firenio.codec.lengthvalue.LengthValueCodec) ChannelConnector(com.firenio.component.ChannelConnector) Channel(com.firenio.component.Channel) ByteBuf(com.firenio.buffer.ByteBuf) LoggerChannelOpenListener(com.firenio.component.LoggerChannelOpenListener)

Aggregations

Channel (com.firenio.component.Channel)33 Frame (com.firenio.component.Frame)28 IoEventHandle (com.firenio.component.IoEventHandle)27 LoggerChannelOpenListener (com.firenio.component.LoggerChannelOpenListener)26 ChannelConnector (com.firenio.component.ChannelConnector)19 LengthValueCodec (com.firenio.codec.lengthvalue.LengthValueCodec)15 LengthValueFrame (com.firenio.codec.lengthvalue.LengthValueFrame)11 NioEventLoopGroup (com.firenio.component.NioEventLoopGroup)10 ChannelAcceptor (com.firenio.component.ChannelAcceptor)9 ByteBuf (com.firenio.buffer.ByteBuf)5 ClientHttpCodec (com.firenio.codec.http11.ClientHttpCodec)5 HttpFrame (com.firenio.codec.http11.HttpFrame)5 ProtobaseCodec (com.firenio.codec.protobase.ProtobaseCodec)5 Waiter (com.firenio.concurrent.Waiter)5 ClientHttpFrame (com.firenio.codec.http11.ClientHttpFrame)4 WebSocketCodec (com.firenio.codec.http11.WebSocketCodec)4 ProtobaseFrame (com.firenio.codec.protobase.ProtobaseFrame)4 ChannelEventListenerAdapter (com.firenio.component.ChannelEventListenerAdapter)4 WebSocketFrame (com.firenio.codec.http11.WebSocketFrame)3 HttpCodec (com.firenio.codec.http11.HttpCodec)2