[ Netty ](三) 基于 webSocket 实现客户端与服务端长连接 (网页聊天实例)

实现客户端与服务端之间建立长连接,通信

  • 1、启动服务端 MyServer
  • 2、启动客户端 client.html
  • 启动客户端时,控制台打印出客户端已连接
  • 客户端显示,与服务端连接已开启
    在这里插入图片描述
    在这里插入图片描述

刷新客户端

  • 客户端与服务端重新建立连接
    在这里插入图片描述

通信测试

  • 向服务端发送消息
  • 服务端接收到消息,控制台打印出消息内容
  • 服务端回复当前时间
    在这里插入图片描述
    在这里插入图片描述

断开连接测试

  • 关闭服务端时,服务端控制台显示连接已断开
    在这里插入图片描述
  • 关闭服务端,客户端显示连接已断开
    在这里插入图片描述

具体的代码实现

客户端

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>WebSocket客户端</title>
</head>
<body>
<script>
    var socket;
    if(window.WebSocket){
        socket = new WebSocket("ws://localhost:8899/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:400px;height:200px"></textarea>

    <input type="button" value="发送数据" onclick="send(this.form.message.value)">

    <h3>服务端输出:</h3>

    <textarea id="responseText" style="width:400px; height:300px"></textarea>

    <input type="button" onclick="javascript:document.getElementById('responseText').value=''" value="清空内容">
</form>
</body>
</html>

服务端

  • MyServer.java
package cust.aowei.netty.fifthexample;

import cust.aowei.netty.fourthexample.MyServerInitializer;
import io.netty.bootstrap.ServerBootstrap;
import io.netty.channel.ChannelFuture;
import io.netty.channel.EventLoopGroup;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.nio.NioServerSocketChannel;
import io.netty.handler.logging.LogLevel;
import io.netty.handler.logging.LoggingHandler;

import java.net.InetSocketAddress;

public class MyServer {
    public static void main(String[] args) throws  Exception{
        //两个线程组
        EventLoopGroup bossGroup = new NioEventLoopGroup();
        EventLoopGroup workerGroup = new NioEventLoopGroup();

        try {
            ServerBootstrap serverBootstrap = new ServerBootstrap();//启动服务器
            serverBootstrap.group(bossGroup, workerGroup).channel(NioServerSocketChannel.class).
                    handler(new LoggingHandler(LogLevel.INFO)). //  指定日志处理器 日志级别 ; handler针对bossGroup
                    childHandler(new WebSocketChannelInitializer());//  childHandler针对workerGroup

            ChannelFuture channelFuture = serverBootstrap.bind(new InetSocketAddress(8899)).sync();//绑定端口
            channelFuture.channel().closeFuture().sync();
        }finally {
            bossGroup.shutdownGracefully();// 关闭线程组
            workerGroup.shutdownGracefully();
        }
    }
}

  • WebSocketChannelInitializer.java
package cust.aowei.netty.fifthexample;

import io.netty.channel.ChannelInitializer;
import io.netty.channel.ChannelPipeline;
import io.netty.channel.socket.SocketChannel;
import io.netty.handler.codec.http.HttpObjectAggregator;
import io.netty.handler.codec.http.HttpServerCodec;
import io.netty.handler.codec.http.websocketx.WebSocketServerProtocolHandler;
import io.netty.handler.stream.ChunkedWriteHandler;

import java.net.Socket;

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 TextWebSocketFrameHandler());

    }
}

  • TextWebSocketFrameHandler .java
package cust.aowei.netty.fifthexample;

import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;
import io.netty.handler.codec.http.websocketx.TextWebSocketFrame;

import java.time.LocalDate;
import java.time.LocalDateTime;

public class TextWebSocketFrameHandler 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 handlerAdded(ChannelHandlerContext ctx) throws Exception {
        System.out.println("handlerAdd:"+ctx.channel().id().asLongText());
    }

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

    @Override
    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
        System.out.println("异常发生");
        ctx.close();
    }
}


在这里插入图片描述

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值