第二章 构建websocket服务器

ajax轮训,浏览器每隔一段时间发送信息到后端,问有没有数据更新

Long pull,阻塞,客户端发起请求后,服务器不响应的话就卡在那里

websocket:基于HTTP1.1,持久化,一旦链接(一次HTTP请求),服务器可以不断推送消息给客户端

1.websocket服务器

package com.imooc.netty.websocket;

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;
public class WSServer {
    public  static void main(String[] args)  {
        EventLoopGroup boss=new NioEventLoopGroup();
        EventLoopGroup worker=new NioEventLoopGroup();
        try{
        ServerBootstrap serverBootstrap=new ServerBootstrap();
        serverBootstrap.group(boss,worker)
                       .channel(NioServerSocketChannel.class)
                       .childHandler(new WSServerInitializer());
        ChannelFuture channelFuture=serverBootstrap.bind(8088).sync();
        channelFuture.channel().closeFuture().sync();
        }catch (InterruptedException e) {
            e.printStackTrace();
        }finally{
            boss.shutdownGracefully();
            worker.shutdownGracefully(); }
    }
}

2.初始化类

package com.imooc.netty.websocket;

import com.imooc.netty.CustomHander;
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.WebSocketClientProtocolHandler;
import io.netty.handler.codec.http.websocketx.WebSocketServerProtocolHandler;
import io.netty.handler.stream.ChunkedWriteHandler;

public class WSServerInitializer extends ChannelInitializer<SocketChannel> {
    protected void initChannel(SocketChannel ch) throws Exception {
        ChannelPipeline pipeline=ch.pipeline();
        //1.http编码器
        pipeline.addLast(new HttpServerCodec());
        //2.对写大数据流的支持
        pipeline.addLast(new ChunkedWriteHandler());
        //3.对httpMessage的聚合,聚合成FullHttpResquest或者FullHttpReponse
        pipeline.addLast(new HttpObjectAggregator(1024*64));
        //4.WebSocket服务器处理的协议用于指定给客户端连接访问的路由"/ws"
        pipeline.addLast(new WebSocketServerProtocolHandler("/ws"));
        pipeline.addLast(new ChatHandler());
    }
}

3.子处理器

package com.imooc.netty.websocket;

import io.netty.channel.Channel;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;
import io.netty.channel.group.ChannelGroup;
import io.netty.channel.group.DefaultChannelGroup;
import io.netty.handler.codec.http.HttpObject;
import io.netty.handler.codec.http.websocketx.TextWebSocketFrame;
import io.netty.util.concurrent.GlobalEventExecutor;

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

public class ChatHandler  extends
        SimpleChannelInboundHandler<TextWebSocketFrame> {
    private static ChannelGroup clients
                =new DefaultChannelGroup(GlobalEventExecutor.INSTANCE);
    protected void channelRead0(ChannelHandlerContext ctx, TextWebSocketFrame msg) throws Exception {
        //1.任意客户端发消息过来转发所有客户端:
        // 当客户端连接服务器后获取其channel,并且放到ChannelGroup中去管理
        String content=msg.text();
        System.out.println("接收到的数据"+content);
        /*for(Channel channel:clients){
            channel.writeAndFlush(
                    new TextWebSocketFrame(
                            "[服务器在]"+LocalDateTime.now()
                                  +"消息为"+content));
        }*/
        clients.writeAndFlush(
                new TextWebSocketFrame(
                "[服务器在]"+LocalDateTime.now()
                        +"消息为"+content));

    }

    @Override
    public void handlerAdded(ChannelHandlerContext ctx) throws Exception {
        clients.add(ctx.channel());
    }
    @Override
    public void handlerRemoved(ChannelHandlerContext ctx) throws Exception {
        System.out.println("客户端断开,其长id为"+ctx.channel().id().asLongText());
        System.out.println("客户端断开,其短id为"+ctx.channel().id().asShortText());
    }
}

4.前端页面

<body>

<script type="application/javascript">

</script>

</body>

<!DOCTYPE html>
<html>
	<head>
		<meta charset="utf-8" />
		<title></title>
	</head>
	<body>
		<div>发送消息:</div>
		<input type="text" id="msgContent"/>
		<input  type="button" value="点我发送" onclick="CHAT.chat()"/>
		<div>接收消息:</div>
		<div id="recieveMsg" style="background-color: gainsboro;"></div>
	<!--开始相应的js编写-->
	<script type="application/javascript">
	  <!--定义CHAT对象:属性socket,方法init,chat-->
	  window.CHAT={
		  socket:null,
		  init:function(){
			  if(window.WebSocket){
				  CHAT.socket=new WebSocket("ws://192.168.1.102:8088/ws");
				  CHAT.socket.onopen=function(){
				  	console.log("连接成功。。。。");
				  };
				  CHAT.socket.onclose=function(){
				  	console.log("连接关闭。。。。");	
				  };
				  CHAT.socket.onerror=function(){
				  		console.log("发生错误。。。。");
				  };
				  CHAT.socket.onmessage=function(e){
				  			console.log("接到消息"+e.data);
							var recieveMs=document.getElementById("recieveMsg");
							var html=recieveMs.innerHTML;
					         recieveMs.innerHTML=html + "<br/>" + e.data;
				  };
			  }
			  else{
				  alert("浏览器不支持WebSocket协议。。。");
			  }
		  },
		  chat:function(){
			  var msg=document.getElementById("msgContent");
			  CHAT.socket.send(msg.value);
		  }
	  };
	 CHAT.init(); 
	</script>
	</body>
</html>

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值