美文网首页
5.webSocket聊天

5.webSocket聊天

作者: 八颗小牙坏脾气 | 来源:发表于2018-12-16 11:16 被阅读0次

Server

public class Server {

    public static final int INET_PORT = 8888;

    public static void main(String[] args) throws Exception {
        EventLoopGroup boss = new NioEventLoopGroup();
        EventLoopGroup worker = new NioEventLoopGroup();
        ServerBootstrap serverBootstrap = new ServerBootstrap();
        try {
            serverBootstrap.group(boss, worker)
                    .channel(NioServerSocketChannel.class)
                    .handler(new LoggingHandler(LogLevel.INFO))
                    .childHandler(new WebSocketChannelInitializer());
            ChannelFuture channelFuture = serverBootstrap.bind(INET_PORT).sync();
            channelFuture.channel().closeFuture().sync();
        }finally {
            boss.shutdownGracefully();
            worker.shutdownGracefully();
        }
    }
}
public class WebSocketChannelInitializer extends ChannelInitializer<SocketChannel> {
    @Override
    protected void initChannel(SocketChannel ch) throws Exception {
        ChannelPipeline pipeline = ch.pipeline();
        pipeline.addLast(new HttpServerCodec());
        pipeline.addLast(new ChunkedWriteHandler());
        pipeline.addLast(new HttpObjectAggregator(8192));
        pipeline.addLast(new WebSocketServerProtocolHandler("/ws"));
        pipeline.addLast(new WebSocketChannelHandler());
    }
}
public class WebSocketChannelHandler extends SimpleChannelInboundHandler<TextWebSocketFrame> {
    
    @Override
    protected void channelRead0(ChannelHandlerContext ctx, TextWebSocketFrame msg) throws Exception {
        System.out.println("收到消息:" + msg.text());
        ctx.channel().writeAndFlush(new TextWebSocketFrame("服务器时间:" + LocalDateTime.now()));
    }

    @Override
    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
        cause.printStackTrace();
        ctx.close();
    }

    @Override
    public void handlerAdded(ChannelHandlerContext ctx) throws Exception {
        System.out.println("handle added " + ctx.channel().id().asLongText());
    }

    @Override
    public void handlerRemoved(ChannelHandlerContext ctx) throws Exception {
        System.out.println("handle removed " + ctx.channel().id().asLongText());
    }
}

Client

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>WebSocket客户端</title>
</head>
<body>
<script type="text/javascript">
    var socket;
    if (window.WebSocket) {
        socket = new WebSocket("ws://localhost:8888/ws");
        socket.onmessage = function (event) {
            var ta = document.getElementById("responseText");
            ta.value = ta.value + "\n" + event.data;
        }

        socket.onopen = function (event) {
            var ta = document.getElementById("responseText");
            ta.value = "连接开启!";
        }

        socket.onclose = function (event) {
            var ta = document.getElementById("responseText");
            ta.value = ta.value + "\n" + "连接关闭!";
        }
    } else {
        alert("浏览器不支持WebSocket!");
    }
    
    function send(message) {
        if (!window.WebSocket) {
            return;
        }
        if (socket.readyState == WebSocket.OPEN) {
            socket.send(message);
        } else {
            alert("连接尚未开启!");
        }
    }
</script>


    <form onsubmit="return false;">
        <textarea name="message" style="width: 300px; height: 200px;"></textarea>
        <input type="button" value="发送数据" onclick="send(this.form.message.value)">
        <h3>服务端输出:</h3>
        <textarea id="responseText" style="width: 300px; height: 300px"></textarea>
        <input type="button" onclick="javascript:document.getElementById('responseText').value=''" value="清空内容 ">
    </form>
</body>
</html>

相关文章

  • 5.webSocket聊天

    Server Client

  • 聊天

    今天下午因为我的焦虑,和敏妹子聊了一会,发现敏敏最近真是突飞猛进,她的话让我有些顿悟吧。 主要聊了两个方面,一是妈...

  • 聊天

    今天要来玉溪办公积金贷款,农行周末加班,集中办理房贷业务。 早上七点半起床,外面下着雨,我催老公快点去,他说外面下...

  • 聊天

    饭后,与女儿一起在小区里溜达,碰到她同学和同学妈妈,一起聊天。 她们一家被评为孝心家庭,很感人。她的婆婆生病五六年...

  • 聊天

    17岁出来工作 踩单车 过两年创业 创业失败继续赚钱继续创业 半年销售 两年运营 选品 上架策略 凤凰教人筑巢故事...

  • 聊天

    我们终于有时间谈一些事 谈爱情、谈理想和人生 谈我老家山上那倒墙的黄泥屋 谈所有人都谈论或不谈论的事 我们都很老了...

  • 聊天

    最近准备跨考电影学 却实实在在是我大学以来比较浪的一段日子 天天都有聚会,聊天 或许这就是很多外向人的日常 对我这...

  • 聊天

    聊天其实就是讲话,语言沟通。 和一个三观相似的朋友聊天,是一种学习,是一种对自己的充电,感受的是快乐,开心,满满的...

  • 聊天

    很久不见的朋友,偶尔QQ上会搭讪几句,突然说要请吃饭。 也行吧,兴许有什么事情呢?难道因为对方是个男的要有所顾忌?...

  • 聊天

网友评论

      本文标题:5.webSocket聊天

      本文链接:https://www.haomeiwen.com/subject/yzbtkqtx.html