notice spring4 It is said that we have supported websocket 了 , After a try, all kinds of pits , Not as good as servlet Simple , Write an article to explain the pit you met .

Environmental Science :tomcat8+spring4.1.6+jdk8+nginx1.8.0

First, I looked at the realization of people on the Internet , all sorts of strange things , Just go straight to spring On the official documents of , Look at their official implementation , But I use springmvc, Always fail , I can't find the request , All page requests were not found , Find out why WebSocketConfig In succession AbstractWebSocketMessageBrokerConfigurer You need to add a comment on springMVC Support for , namely @EnableWebMvc, With you in spring There is a use for scanning the configuration package in the configuration file . I don't say much nonsense , On the first code .

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
import  org.springframework.context.annotation.Configuration;
import  org.springframework.messaging.simp.config.MessageBrokerRegistry;
import  org.springframework.web.servlet.config.annotation.EnableWebMvc;
import  org.springframework.web.socket.config.annotation.*;
  
@Configuration
@EnableWebMvc
@EnableWebSocketMessageBroker
public  class  WebSocketConfig  extends  AbstractWebSocketMessageBrokerConfigurer {
  
     @Override
     public  void  configureMessageBroker(MessageBrokerRegistry config) {
         config.enableSimpleBroker( "/tweet" );
         config.setApplicationDestinationPrefixes( "/websocket" );
     }
  
     public  void  registerStompEndpoints(StompEndpointRegistry registry) {
         registry.addEndpoint( "/hello" ).withSockJS();
     }
  
}

Above is websocket Configuration class , Here's the request .

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
import  com.yuorfei.bean.ResultData;
import  org.apache.commons.logging.Log;
import  org.apache.commons.logging.LogFactory;
import  org.springframework.messaging.handler.annotation.MessageMapping;
import  org.springframework.messaging.handler.annotation.SendTo;
import  org.springframework.stereotype.Controller;
  
@Controller ( "chat" )
public  class  ChatAction {
  
     private  static  final  Log log = LogFactory.getLog(MessageAction. class );
  
     @MessageMapping ( "/hello" )
     @SendTo ( "/tweet/fuck" )
     public  ResultData chat(String message)  throws  Exception {
         long  time = System.currentTimeMillis();
         log.info(time+ ":" +message);
         return  new  ResultData(time, true ,message);
     }
  
}

Write the front-end code when the request class is ready :

Front end code needs to be introduced js Yes sockjs-1.0.3.min.js,stomp.min.js Two , Just go to the latest website , I'm using the latest .

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
<! DOCTYPE  html>
< html >
< head >
     < meta  charset = "utf-8" >
     < meta  http-equiv = "X-UA-Compatible"  content = "IE=edge" >
     < script  src = "/dest/js/fun/chat/sockjs-1.0.3.min.js" ></ script >
     < script  src = "/dest/js/fun/chat/stomp.min.js" ></ script >
     <!--  For convenience ,js I just put it here  -->
     < script >
         var stompClient = null;
             
         function setConnected(connected) {
             document.getElementById('connect').disabled = connected;
             document.getElementById('disconnect').disabled = !connected;
             document.getElementById('conversationDiv').style.visibility = 
                 connected ? 'visible' : 'hidden';
             document.getElementById('response').innerHTML = '';
         }
             
         function connect() {
             var socket = new SockJS('/hello');
             stompClient = Stomp.over(socket);
             stompClient.connect({}, function(frame) {
                 setConnected(true);
                 console.log('Connected: ' + frame);
                 stompClient.subscribe('/tweet/fuck', function(greeting){
                     showGreeting(JSON.parse(greeting.body).code+" : "+
                         JSON.parse(greeting.body).message);
                 });
             });
         }
             
         function disconnect() {
             if (stompClient != null) {
                 stompClient.disconnect();
             }
             setConnected(false);
             console.log("Disconnected");
         }
             
         function sendMessage() {
             var message = document.getElementById('message').value;
             stompClient.send("/websocket/hello", {}, JSON.stringify({ 'message': message }));
         }
     
         function showGreeting(message) {
             var response = document.getElementById('response');
             var p = document.createElement('p');
             p.style.wordWrap = 'break-word';
             p.appendChild(document.createTextNode(message));
             response.appendChild(p);
         }
     </ script >
</ head >
< body  onload = "disconnect()" >
     < noscript >
         < h2  style = "color: #ff0000" > Unsupported browser version , Ya's is not to use IE 了 , You're ruining the lives of programmers </ h2 >
     </ noscript >
     
     < a  href = "${homeUrl!" /"}">< h5 > Return to and or not the home page of the website </ h5 ></ a >
     < hr />
     
     < p > It's just a SpringMVC Of websocket Example </ p >
     
     < div >
         < div >
             < button  id = "connect"  onclick = "connect();" > Connect </ button >
             < button  id = "disconnect"  disabled = "disabled"  onclick = "disconnect();" >
             disconnect </ button >
         </ div >
         < div  id = "conversationDiv" >
             < label > What do you want to say? </ label >< input  type = "text"  id = "message"  />
             < button  id = "sendMessage"  onclick = "sendMessage();" > send out </ button >
             < p  id = "response" ></ p >
         </ div >
     </ div >
     < hr />
</ body >
</ html >

When we get here ok 了 , But the operation found that it would report an error , The translation of the error message roughly means : No introduction jackson2 My bag perhaps socket Message transformation is not configured .

Suddenly, I didn't introduce jackson2, hurriedly maven hold jackson2 Add in the dependence of , I used it a long time ago jackson, But I don't know 2 It only introduces core Of jar You can't have a bag , It also needs to be

jackson-databind and jackson-annotations, For the convenience of me, I just joined in ( It's big enough , Not as good as fastjson Refreshing ).

So you ok 了 , Send a message after configuration , Normal reception , Handle ,ok, The console doesn't report annoying mistakes

spring4 Use websocket More articles about

  1. spring4 Use websocket

    What to learn : sockjs, For the lower version of ie Etc. not supported websocket Browser , use js simulation websocket Object to achieve compatibility ( In fact, there are also polling situations ).sockjs Address https://githu ...

  2. tomcat Supported by websocket service

    First episode : Personal blog stay tomcat7 Later versions , Write a websocket The service program is very easy —— As shown in the following code , When the client establishes a connection and sends something to the server , The server will return a string every two seconds “world”. ...

  3. web im 2-- be based on Spring websocket achieve web The chat room

    As used in this article ,Spring4 and websocket To build web The chat room , According to the framework SpringMVC+Spring+Hibernate Of Maven project , The background to use spring websocket Forward messages and chat ...

  4. spring4+websocket+nginx Detailed configuration

    Implemented version jdk1.7.0_25, tomcat7.0.47.0, Tengine/2.1.1 (nginx/1.6.2), servlet3.0, spring4.2.2 Use maven Import version 3. ...

  5. spring4 security 4 +websocket Single sign on

    Address of the test :http://sms.reyo.cn/ Account number :aa password :123456 First look at the renderings : spring4 security 4 Single sign on , and websocket Realize single point offline notification

  6. spring4.0 Nine :websocket Simple application

    Spring 4.0 One of the biggest updates to is the addition of websocket Support for .websocket Provides an in web High efficiency in application . Two way communication , You need to think about the client ( browser ) High frequency and low latency message exchange with server . Generally speaking, we should ...

  7. spring WebSocket Detailed explanation

    scene websocket yes Html5 One of the new features , The purpose is to establish full duplex communication between browser and server , solve http request - Response leads to excessive resource consumption , At the same time, it provides a new way to realize the special scene application , Like chatting . Stock Exchange . game ...

  8. spring+websocket Integrate

    java-websocket It's very easy to build , Children's shoes without frame can be downloaded here, which are adjusted by the master himself java-websocket Program : Apach Tomcat 8.0.3+MyEclipse+maven+JD ...

  9. Spring4 A brief introduction to the new features

    Spring It's a java It's extremely popular in the world Open source framework of .Spring The original intention is to reduce the complexity of enterprise development , And try to get through POJO Before object implementation EJB This kind of heavy framework can achieve the function .Spring It's not just about service End development is useful , ...

Random recommendation

  1. JSP visit Spring Medium bean

    JSP visit Spring Medium bean <%@page import="com.sai.comment.po.TSdComment"%> <%@page import ...

  2. Spring Boot A test case for

    package tk.mybatis.springboot.mapper; import org.junit.Assert; import org.junit.Test; import org.jun ...

  3. css Three layouts

    The first layout : Standard flow ( The document flow ) Standard flow is the default display of elements . For example, block level elements occupy a single line , In line elements can be displayed in one line . The second layout : float ,float attribute Floating corresponding to css The attribute is float:left/righ ...

  4. open_basedir restriction in effect, solve php Introduce file permission problem

    One . Preface In today's Ubuntu Installed lnmp Environmental Science , When running a project, there's , introduce 500 Error of Two . Error checking Add... To the project file entry , The code shows the error content , Check out the error ini_set('display_error ...

  5. Wi-Fi Mesh Network technology

    Wi-Fi It was introduced very early mesh technology , And it's getting more and more attention recently . Google .Eero.Linksys.Netgear And almost all online brands that target homes and small offices offer mesh grid system . But there are ...

  6. 【BZOJ3551】 [ONTAK2010]Peaks Enhanced Edition

    BZOJ3551 [ONTAK2010]Peaks Enhanced Edition Solution Kruscal After reconstructing the tree, we find that we can discretize and then multiply for less than + The chairman tree finds the feasible solution of the previous one . And then it's all right . If the array is not well opened , Easy in ...

  7. P1002 Who got the most Scholarships

    P1002  Who got the most Scholarships Time : 1000ms /  Space : 131072KiB / Java Class name : Main background NOIP2005 The first question of the improvement group in the second round describe The practice of a school is to give out prizes after the final examination of each semester ...

  8. Mybatis Note 8 :MyBatis in #{} and ${} The difference between

    Let's first introduce MyBatis in #{} and ${} The difference between , The details are as follows : 1. $ Generate the incoming data directly in the sql in 2. # To a great extent sql Inject . 3.$ Method cannot prevent Sql Inject . 4.$ The way is average ...

  9. CH4402 Small Z Socks of ( Mo team )

    describe As a casual person , Small Z It takes a long time every morning to find a pair of colorful socks to wear . One day at last , Small Z I can't stand the annoying process of looking for socks any more , So he decided to let it be -- say concretely , Small Z Put this N A sock from the 1 To N Number , ...

  10. nwafu - java Internship JDBC practice - Student information system interface

    The realization of student information system interface - JDBC writer:pprp The implementation of login interface : In two parts : 1.LoginFrame.java : use windowbuilder Quickly build the interface , Build a login interface , ...