Netty4 Simple construction of WebSocket service

Source: Internet
Author: User

Websocket.server.RandomResponseGenerator.java

package websocket.server;import  io.netty.channel.channelhandlercontext;import io.netty.handler.codec.http.websocketx.textwebsocketframe; import java.util.random;import org.apache.log4j.logger;public class  randomresponsegenerator extends thread{private channelhandlercontext ctx;private  Random random = new random ();p rivate int messagecount = 10;public  randomresponsegenerator (channelhandlercontext ctx) {this.ctx=ctx;} Private logger logger = logger.getlogger (randomresponsegenerator.class);p ublic void  run ()  {while (messagecount-->0) {Ctx.writeandflush (New textwebsocketframe ("[Server] the  random value is :  (+random.nextint)); try {thread.sleep (1000);}  catch  (interruptedexception e)  {logger.error ("Encounter an exception", E);}}} 

websocket.server.httprequesthandler.java

package websocket.server;import io.netty.channel.channelhandlercontext;import  Io.netty.channel.simplechannelinboundhandler;import io.netty.handler.codec.http.fullhttprequest;import  org.apache.log4j.Logger;public class HttpRequestHandler extends  simplechannelinboundhandler<fullhttprequest> {         private final string wsuri;        public  Httprequesthandler (String wsuri)  {        this.wsuri =  wsUri;    }        private Logger  Logger = logger.getlogger (Httprequesthandler.class);         @Override     protected void channelread0 (final channelhandlercontext  CTX,&NBSP;FULLHTTPREQUEST&NBSP;MSG)             throws Exception {             if (Wsuri.equalsignorecase (Msg.geturi ())) {         logger.info ("a websocket connection established ... ");         logger.info ("the request uri is : " +msg.getUri ()) ;                new  Randomresponsegenerator (CTX). Start ();                     ctx.firechannelread (Msg.retain ());         }    }}

websocket.server.textwebsocketframehandler.java

package websocket.server;import io.netty.channel.channelhandlercontext;import  io.netty.channel.simplechannelinboundhandler;import  io.netty.handler.codec.http.websocketx.textwebsocketframe;import org.apache.log4j.logger;public  Class textwebsocketframehandler extends simplechannelinboundhandler<textwebsocketframe>  {        private Logger logger =  Logger.getlogger (textwebsocketframehandler.class);         @Override     protected void channelread0 (channelhandlercontext ctx,   &NBSP;&NBSP;&NBSP;&NBSP;&NBSP;&NBSP;&NBSP;&NBSP;&NBSP;&NBSP;TEXTWEBSOCKETFRAME&NBSP;MSG)  throws  Exception {    string message = msg.content (). ToString ( Io.netty.util.CharsetUtil.UTF_8);     logger.info ("Receive below information  from client:\n "+message");         ctx.writeandflush (new TextWebSocketFrame ("[server] receive message [" +message+ "] successfully"));     }}

websocket.server.websocketserverinitializer.java

package websocket.server;import io.netty.channel.channel;import  io.netty.channel.channelinitializer;import io.netty.channel.channelpipeline;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 websocketserverinitializer extends  ChannelInitializer<Channel> {      @Override      Protected void initchannel (channel ch)  throws Exception {         channelpipeline pipeline = ch.pipeline ();                  pipeline.addlast (new  Httpservercodec ());             &nbsP;    pipeline.addlast (New chunkedwritehandler ());                  pipeline.addlast (new  Httpobjectaggregator (64*1024));                  pipeline.addlast (New httprequesthandler ("/ws"));                  pipeline.addlast (new  Websocketserverprotocolhandler ("/ws"));                  pipeline.addlast (New textwebsocketframehandler ());              } }

Pom.xml

<dependencies><dependency><groupid>log4j</groupid><artifactid>log4j</ Artifactid><version>1.2.14</version></dependency><dependency><groupid> commons-logging</groupid><artifactid>commons-logging</artifactid><version>1.1.1</ Version></dependency><dependency><groupid>io.netty</groupid><artifactid> Netty-all</artifactid><version>4.0.29.final</version></dependency></dependencies >


Using HTML5 as the WebSocket front-end implementation

Index.html

<! doctype html>


Netty4 Simple construction of WebSocket service

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.