Practical experience of WebSocket combined with hibernate + spring + json

Source: Internet
Author: User
Tags maven central

Recently, a web game was created as needed. In a certain period of time, the page needs to be refreshed in real time. Currently, the general idea of website creation is to use js polling. Because it is an innovative small project, friends in the same group proposed the WebSocket mentioned in html5. they first conducted technical research. Currently, java does not support many websockets. Few websocket implementation frameworks can be found on the Internet. Added WebSocket to java EE7. Therefore, all packages come from tomcat support. At least three packages of tomcat-coyote, tomcat-catalina, and tomcat-annotations-api are required. Because tomcat supports websocket better since version 7.027, in versions earlier than tomcat, websocket can be used, but various problems may occur. For example, after a websocket connection is established, the connection is closed after several seconds. Therefore, a better choice is to use version 7.027 or above. These three jar packages are available in the corresponding tomcat lib folder. I have been familiar with maven since I was a graduate student, and I have to sigh here. Because it is a small agile team, version control is required. In terms of jar package control, you still want to use maven to control it. You can directly search for the maven central database. There are still some. After the group discussion, I decided to use tomcat7.039 (it seems that 40 has come out), which solved the issue of version control and jar package configuration. Pom:

         <dependency>             <groupId>org.apache.tomcat</groupId>             <artifactId>tomcat-coyote</artifactId>             <version>7.0.39</version>         </dependency>         <dependency>              <groupId>org.apache.tomcat</groupId>              <artifactId>tomcat-catalina</artifactId>               <version>7.0.39</version>         </dependency>         <dependency>               <groupId>org.apache.tomcat</groupId>              <artifactId>tomcat-annotations-api</artifactId>              <version>7.0.39</version>         </dependency>

The next step is to solve the architecture problem. Currently, there are few practices on websocket on the Internet. Basically, we can find the websocket architecture and very simple examples (websocket example is provided in tomcat). How can we apply the websocket mechanism. First, the basic framework is designed to use hibernate + spring mvc in combination with websocket. However, in actual experiments, there may be some conflicts between spring mvc and websocket. This is because JDK 8 and WebSocket programming are supported only in the versions released by Spring Framework 4.0 some time ago. So at this stage, we need other methods to implement spring mvc + websocket. A simple solution is to write a tool class to manually obtain the bean. Solve the websocket interaction mode that needs to be solved after spring and websocket support. The two most direct websocket methods are onTextMessage and onBinaryMessage, that is, byte stream transmission and bytes stream transmission. The optimal method is to design a self-transmission protocol. Transmission Through byte streams. The frontend and backend parse protocols to obtain interactive Operations respectively. Next, you can write a post on onTextMessage, that is, the publish stream. Json can be well supported.

To configure websocket:

1. Implement a class that inherits ContextLoaderListener and configures

          SpringLoaderListener                               ServletContext context=         ApplicationContext ctx=             }

Web. xml

   <listener>         <listener->          </listener-> </listener>

Obtain the spring bean tool class:

                                              SpringContextutil.context =             Object getBean(String name)                @SuppressWarnings("unchecked"       Object getBean(String name, Class requiredType)                                          isSingleton(String name)                   @SuppressWarnings("unchecked"       Class getType(String name)                     String[] getAliases(String name)                  }

Introduce the jar package required for json:

     <dependency>      <groupId>com.google.code.gson</groupId>       <artifactId>gson</artifactId>       <version>2.2.3</version>     </dependency>     <dependency>         <groupId>net.sf.json-lib</groupId>         <artifactId>json-lib</artifactId>         <version>2.4</version>     </dependency>     <dependency>      <groupId>net.sf.ezmorph</groupId>       <artifactId>ezmorph</artifactId>       <version>1.0.6</version>     </dependency>    

Two files must be added to the backend to inherit WebSocketServlet:

       @WebServlet("/room"   RoomSocketServlet               serialVersionUID = -5853470534275847275L                                     }

One inherits MessageInbound:

   RoomMessageInbound                                     (commandDispatcher ==              commandDispatcher = (CommandDispatcherUtils) SpringContextutil.getBean("commandDispatcher"             room = RoomListModel.getInstance().getRoom(0                                     onClose(                  onBinaryMessage(ByteBuffer buffer)            onTextMessage(CharBuffer buffer)        String msg =       JSONObject report =       TemplateCommand command = commandDispatcher.getCommandByKey(report.getString("command"    }

You can use JSONObject report = JSONObject. fromObject (msg) to convert a string to a json object. This means that the real-time object information is transmitted through websocket.

In the front-end page, you only need to add

          roomsocket =  WebSocket('ws://127.0.0.1:8080/XXXX/room); }

JSON. stringify (data) can be converted to json when the front-end sends data to the backend.

The above code has been removed a lot. So the code can be used without being copied. Only provides a solution. In addition, the new java version or Spring Framework 4.0 will be able to easily support the implementation of websocket. I will summarize my websocket research during this period. With the emergence of various new technologies, real-time web technology has become increasingly mature. Websocket is an important feature of html5. It is worth looking.

 

Related Article

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.