Search in sources :

Example 1 with WebSocketFrame

use of com.firenio.codec.http11.WebSocketFrame 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 2 with WebSocketFrame

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

the class HttpFrameHandle method exceptionCaught.

@Override
public void exceptionCaught(Channel ch, Frame frame, Throwable ex) {
    logger.error(ex.getMessage(), ex);
    frame.release();
    if (!ch.isOpen()) {
        return;
    }
    if (ch.getCodec() instanceof WebSocketCodec) {
        WebSocketFrame f = new WebSocketFrame();
        f.setString((ex.getClass() + ex.getMessage()), ch);
        try {
            ch.writeAndFlush(f);
        } catch (Exception e) {
            logger.error(e.getMessage(), e);
        }
    } else {
        StringBuilder builder = new StringBuilder();
        builder.append("            <div>oops, server threw an inner exception, the stack trace is :</div>\n");
        builder.append("            <div style=\"font-family:serif;color:#5c5c5c;\">\n");
        builder.append("            -------------------------------------------------------</BR>\n");
        builder.append("            ");
        builder.append(ex.toString());
        builder.append("</BR>\n");
        StackTraceElement[] es = ex.getStackTrace();
        for (StackTraceElement e : es) {
            builder.append("                &emsp;at ");
            builder.append(e.toString());
            builder.append("</BR>\n");
        }
        try {
            printHtml(ch, frame, HttpStatus.C500, builder.toString());
        } catch (Exception e) {
            logger.error(e.getMessage(), e);
        }
    }
}
Also used : WebSocketFrame(com.firenio.codec.http11.WebSocketFrame) IOException(java.io.IOException) WebSocketCodec(com.firenio.codec.http11.WebSocketCodec)

Example 3 with WebSocketFrame

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

the class WebSocketMsgAdapter method doLoop.

@Override
protected void doLoop() throws InterruptedException {
    Msg msg = (Msg) msgs.poll(16, TimeUnit.MILLISECONDS);
    if (msg == null) {
        return;
    }
    if (msg.ch != null) {
        WebSocketFrame f = new WebSocketFrame();
        f.setString(msg.msg, msg.ch);
        try {
            msg.ch.writeAndFlush(f);
        } catch (Exception e) {
            logger.error(e.getMessage(), e);
        }
    } else {
        if (!clientMap.isEmpty()) {
            synchronized (this) {
                Client client = clientMap.values().iterator().next();
                Channel ch = client.channel;
                WebSocketFrame f = new WebSocketFrame();
                byte[] data = msg.msg.getBytes();
                f.setContent(data);
                try {
                    ByteBuf buf = ch.getCodec().encode(ch, f);
                    ChannelManagerListener.broadcast(buf, channelMap.values());
                } catch (Exception e) {
                    logger.error(e.getMessage(), e);
                }
            }
        }
    }
}
Also used : Channel(com.firenio.component.Channel) WebSocketFrame(com.firenio.codec.http11.WebSocketFrame) ByteBuf(com.firenio.buffer.ByteBuf)

Example 4 with WebSocketFrame

use of com.firenio.codec.http11.WebSocketFrame 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 5 with WebSocketFrame

use of com.firenio.codec.http11.WebSocketFrame 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)

Aggregations

WebSocketFrame (com.firenio.codec.http11.WebSocketFrame)5 HttpFrame (com.firenio.codec.http11.HttpFrame)3 Channel (com.firenio.component.Channel)3 JSONObject (com.alibaba.fastjson.JSONObject)2 WebSocketCodec (com.firenio.codec.http11.WebSocketCodec)2 ByteBuf (com.firenio.buffer.ByteBuf)1 ClientHttpCodec (com.firenio.codec.http11.ClientHttpCodec)1 ClientHttpFrame (com.firenio.codec.http11.ClientHttpFrame)1 WsUpgradeRequestFrame (com.firenio.codec.http11.WsUpgradeRequestFrame)1 ChannelConnector (com.firenio.component.ChannelConnector)1 Frame (com.firenio.component.Frame)1 IoEventHandle (com.firenio.component.IoEventHandle)1 LoggerChannelOpenListener (com.firenio.component.LoggerChannelOpenListener)1 NioEventLoopGroup (com.firenio.component.NioEventLoopGroup)1 IOException (java.io.IOException)1 HashMap (java.util.HashMap)1 Client (sample.http11.service.WebSocketMsgAdapter.Client)1