netty 웹 소켓 서버 구현

8380 단어 netty
의지 하 다
springboot 개발 을 사용 하여 상용 starter 외 에 netty-websocket-spring-boot-starter 도 있 습 니 다.

		    org.yeauty
		    netty-websocket-spring-boot-starter
		    0.8.0


채널 클래스
MyChannel HandlerPool 은 모든 채널 을 관리 합 니 다.
import io.netty.channel.group.ChannelGroup;
import io.netty.channel.group.DefaultChannelGroup;
import io.netty.util.concurrent.GlobalEventExecutor;

/**
 * MyChannelHandlerPool
 *     ,    websocket  
 */
public class MyChannelHandlerPool {

    public MyChannelHandlerPool(){}

    public static ChannelGroup channelGroup = new DefaultChannelGroup(GlobalEventExecutor.INSTANCE);

}


채널 논리 처리 클래스
MyWebSocketHandler 주요 서버 와 클 라 이언 트 가 채널 을 만 든 후의 작업
import java.util.HashMap;
import java.util.Map;

import org.springframework.stereotype.Component;

import com.alibaba.fastjson.JSON;

import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;
import io.netty.handler.codec.http.FullHttpRequest;
import io.netty.handler.codec.http.websocketx.TextWebSocketFrame;
@Component
public class MyWebSocketHandler extends SimpleChannelInboundHandler {

    @Override
    public void channelActive(ChannelHandlerContext ctx) throws Exception {
        System.out.println("        ,    !");

        //   channelGroup   
        MyChannelHandlerPool.channelGroup.add(ctx.channel());
    }

    @Override
    public void channelInactive(ChannelHandlerContext ctx) throws Exception {
        System.out.println("        ,    !");
        //   channelGroup    
        MyChannelHandlerPool.channelGroup.remove(ctx.channel());
    }

    @Override
    public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
        //     FullHttpRequest,    
        if (null != msg && msg instanceof FullHttpRequest) {
            FullHttpRequest request = (FullHttpRequest) msg;
            String uri = request.uri();

            Map paramMap=getUrlParams(uri);
            System.out.println("       :"+JSON.toJSONString(paramMap));
            //  url    ,    
            if(uri.contains("?")){
                String newUri=uri.substring(0,uri.indexOf("?"));
                System.out.println(newUri);
                request.setUri(newUri);
            }

        }else if(msg instanceof TextWebSocketFrame){
            //   TEXT    
            TextWebSocketFrame frame=(TextWebSocketFrame)msg;
            System.out.println("          :" +frame.text());
            sendAllMessage(frame.text());
        }
        super.channelRead(ctx, msg);
    }

    @Override
    protected void channelRead0(ChannelHandlerContext channelHandlerContext, TextWebSocketFrame textWebSocketFrame) throws Exception {

    }

    public void sendAllMessage(String message){
        //     ,     channel
        MyChannelHandlerPool.channelGroup.writeAndFlush( new TextWebSocketFrame(message));
    }

    private static Map getUrlParams(String url){
        Map map = new HashMap<>();
        url = url.replace("?",";");
        if (!url.contains(";")){
            return map;
        }
        if (url.split(";").length > 0){
            String[] arr = url.split(";")[1].split("&");
            for (String s : arr){
                String key = s.split("=")[0];
                String value = s.split("=")[1];
                map.put(key,value);
            }
            return  map;

        }else{
            return map;
        }
    }
}


서비스 설정 클래스
Netty Server 에서 netty 를 자주 설정 합 니 다.
import io.netty.bootstrap.ServerBootstrap;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.ChannelOption;
import io.netty.channel.EventLoopGroup;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioServerSocketChannel;
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;

public class NettyServer {
	 private final int port;
	 
	    public NettyServer(int port) {
	        this.port = port;
	    }
	 
	    public void start() throws Exception {
	        EventLoopGroup bossGroup = new NioEventLoopGroup();
	 
	        EventLoopGroup group = new NioEventLoopGroup();
	        try {
	            ServerBootstrap sb = new ServerBootstrap();
	            sb.option(ChannelOption.SO_BACKLOG, 1024);
	            sb.group(group, bossGroup) //      
	                    .channel(NioServerSocketChannel.class) //      channel
	                    .localAddress(this.port)//       
	                    .childHandler(new ChannelInitializer() { //              
	 
	                        @Override
	                        protected void initChannel(SocketChannel ch) throws Exception {
	                            System.out.println("     ");
	                            //websocket       http   ,        http    
	                            ch.pipeline().addLast(new HttpServerCodec());
	                            //           
	                            ch.pipeline().addLast(new ChunkedWriteHandler());
	                            ch.pipeline().addLast(new HttpObjectAggregator(8192));
	                            ch.pipeline().addLast(new WebSocketServerProtocolHandler("/ws", null, true, 65536 * 10));
	                            ch.pipeline().addLast(new MyWebSocketHandler());
	                        }
	                    });
	            ChannelFuture cf = sb.bind().sync(); //          
	            System.out.println(NettyServer.class + "       : " + cf.channel().localAddress());
	            cf.channel().closeFuture().sync(); //        
	        } finally {
	            group.shutdownGracefully().sync(); //        
	            bossGroup.shutdownGracefully().sync();
	        }
	    }
}


springboot 시작 클래스
DemoApplication 시작 클래스(@Enable Scheduling 은 정시 작업 을 사용 할 때의 주석 입 니 다.무시 할 필요 가 없습니다)
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.scheduling.annotation.EnableScheduling;

import com.nk.netty.NettyServer;
@SpringBootApplication
@EnableScheduling
public class DemoApplication {
	public static void main(String[] args) {
		SpringApplication.run(DemoApplication.class,args);
		try {
			new NettyServer(8000).start();
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
}

클 라 이언 트
주로 js 코드

 	 var testdata;
    $(function(){ 
        var websocket = null;
        var host = document.location.host;
        //           WebSocket 
        var websocket = null;  
              if('WebSocket' in window) {
                  websocket = new WebSocket("ws://   ip:    /ws"); 
              } else if('MozWebSocket' in window) {
                  websocket = new MozWebSocket("ws://   ip:    /ws");              
              } else {
                  websocket = new SockJS("ws://   ip:    /ws");
              }

        //            
        websocket.onerror = function() {
        };

        //            
        websocket.onopen = function() {
        }

        //           
        websocket.onmessage = function(event) {
          console.log(event.data)
          testdata = JSON.parse(event.data)
          $(".name:eq("+testdata.id+")").text(testdata.v)
        }

        //          
        websocket.onclose = function() {
          setMessageInnerHTML("WebSocket    ");
        }

        //        ,      ,     websocket  ,             ,server     。 
        window.onbeforeunload = function() {
          closeWebSocket();
        }

        //  WebSocket   
        function closeWebSocket() {
          websocket.close();
        }
        
    });

좋은 웹페이지 즐겨찾기