Tomcat8+websocket Demo __websocket

Source: Internet
Author: User
Tags session id sendmsg sessions syslog throwable

Reference Documentation:

Http://wenku.baidu.com/view/4e3d2d34915f804d2a16c119.html

http://tools.ietf.org/html/rfc6455

Http://www.infoq.com/cn/news/2013/07/ee7-websocket-support


Tomcat8 truly supports jsr-356 (including support for websocket), TOMCAT7 Partial versions of WebSocket implementations are incompatible jsr-356.

Be aware of websocket compatibility issues with browsers, some earlier versions of browsers support older versions of the WebSocket protocol and may be incompatible with the new version of WebSocket. The blogger adopts the "Chrome version 33.0.1750.117 m" Test.

WebSocket is said to have changed and may even be independent from HTML5, so the current code is not guaranteed to execute in the future.

Because the blogger uses eclipse that does not support TOMCAT8, it uses Idea 13 development (Tomcat8.0.3+jdk7+servlet 3.0).


Endpoint's session is not a servlet's session,endpoint session more like a separate count, endpoint how to use the servlet session is still being tested.

Package org.sl.action;
Import Javax.servlet.ServletConfig;
Import javax.servlet.ServletException;
Import Javax.servlet.annotation.WebInitParam;
Import Javax.servlet.annotation.WebServlet;
Import Javax.servlet.http.HttpServlet;
Import Javax.servlet.http.HttpServletRequest;
Import Javax.servlet.http.HttpServletResponse;
Import javax.servlet.http.HttpSession;
Import java.io.IOException;

Import Java.io.PrintWriter;
 /** * Created by shanl on 14-3-2. * * @WebServlet (name= "helloaction", urlpatterns={"/helloaction"},loadonstartup=1, initparams={@Web Initparam (name= "name", value= "Xiazdong"), @WebInitParam (name= "age", value= ")"}) public class Helloaction Extends HttpServlet {protected void service (HttpServletRequest request, httpservletresponse response) throws Servlete
        Xception, IOException {servletconfig config = getservletconfig ();
        HttpSession session = Request.getsession ();
      PrintWriter out = Response.getwriter ();  Out.println (" 

Package org.sl.action;
Import javax.websocket.*;
Import Javax.websocket.server.ServerEndpoint;

Import java.io.IOException;
 /** * Created by shanl on 14-3-2. *//@ServerEndpoint (value = "/websocket1action") public class Websocket1action extends Endpoint {private session SES
    Sion
    private static final Logger Syslogger = Logger.getlogger ("SysLog");
    @Override public void OnClose (sessions session, Closereason Closereason) {System.out.println ("onClose"); @Override public void OnError (Session session, Java.lang.Throwable Throwable) {System.out.println ("one
    Rror "); @Override public void OnOpen (sessions session, Endpointconfig config) {//syslogger.info ("* * WebSocket
        Closed from SessionId "+ this.session.getId ());

        Remoteendpoint.basic remote = Session.getbasicremote ();
        System.out.println ("Pathparams:" +session.getpathparameters ()); System.out.println ("Requestparams" +session.getrequestparameterMap ());
        Session.addmessagehandler (new Mymessagehandle (remote));
            /*** try{System.out.println ("OnOpen");
            System.out.println (Session.getquerystring ());
            System.out.println (Session.getrequestparametermap ());
            Session.getbasicremote (). Getsendwriter (). Write ("Success");
        Session.getbasicremote (). SendText ("Success");
        }catch (Exception ex) {ex.printstacktrace (); } ***/} Private class Mymessagehandle implements Messagehandler.whole<string> {Remoteend Point.
        Basic remote = NULL;
        Public Mymessagehandle (Remoteendpoint.basic remote) {this.remote = remote; @Override public void OnMessage (String s) {try {remote.sendtext ("success")
            );
            catch (IOException e) {e.printstacktrace ();
 }
        }
    }
}

Package org.sl.action;
Import javax.websocket.*;
Import Javax.websocket.server.ServerEndpoint;

Import java.io.IOException;
 /** * Created by shanl on 14-3-2.
    * * @ServerEndpoint (value = "/websocket2") public class Websocket2action {private sessions session;

    private static final Logger Syslogger = Logger.getlogger ("SysLog");

        @OnOpen public void Open (Session session,endpointconfig config) {this.session = session;
    Syslogger.info ("* * * WebSocket opened from sessionId" + Session.getid ()); @OnMessage public void Inmessage (session session,string message) {//syslogger.info ("* * WebSocket rece
        Ived from SessionId "+ this.session.getId () +": "+ message);
        System.out.println ("rece:" +message);
        try {session.getbasicremote (). SendText ("Success");
        catch (IOException e) {e.printstacktrace (); @OnClose public void End (Session session) {//syslogger.info ("** * WebSocket closed from sessionId "+ this.session.getId ());
 }

}

Package org.sl.action;

Import org.omg.cosnaming._namingcontextextstub;
Import javax.websocket.*;

Import Javax.websocket.server.ServerEndpoint;
 /** * Created by shanl on 14-3-3.
        */@ServerEndpoint (value= "/echoendpoint") public class Echoendpoint {@OnOpen public void start {
    System.out.println ("Session" +session.getid () + "open."); 
        @OnMessage public void Process (session session, String message) {System.out.println ("rece:" + message);
        Remoteendpoint.basic remote = Session.getbasicremote ();
        int c = integer.valueof (message);
                for (int i=1; i<=c; i++) {try {remote.sendtext ("response" +i);
            Thread.Sleep (500);
            catch (Exception e) {e.printstacktrace (); @OnClose public void End (Session session) {SYSTEM.OUT.PRINTLN (+session.getid) (

    ) + "close."); @OnError public void Error (Session sessions, java.lang.Throwable Throwable) {System.err.println ("session" +session.getid () + "error:" +throwa
    BLE);
 }
}




<%--Created by the IntelliJ idea. --%>
<%@ page contenttype= "Text/html;charset=utf-8" language= "java"%>

<! DOCTYPE html>  

<! DOCTYPE html>  

<! DOCTYPE html>  



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.