1+ <%@ taglib prefix =" spring" uri =" http://www.springframework.org/tags" %>
2+ <html >
3+ <head >
4+ <title >Chat WebSocket</title >
5+
6+ <spring:url value =" /resources/js/sockjs-0.3.4.js" var =" sockjs" />
7+ <spring:url value =" /resources/js/stomp.js" var =" stomp" />
8+
9+ <script src =" ${ sockjs } " ></script >
10+ <script src =" ${ stomp } " ></script >
11+
12+ <script type =" text/javascript" >
13+
14+ var stompClient = null ;
15+
16+ function setConnected (connected ) {
17+
18+ document .getElementById (' connect' ).disabled = connected;
19+ document .getElementById (' disconnect' ).disabled = ! connected;
20+ document .getElementById (' conversationDiv' ).style .visibility = connected ? ' visible' : ' hidden' ;
21+ document .getElementById (' response' ).innerHTML = ' ' ;
22+ }
23+
24+ function connect () {
25+
26+ var socket = new SockJS (' /spring-mvc-java/chat' );
27+ stompClient = Stomp .over (socket);
28+
29+ stompClient .connect ({}, function (frame ) {
30+
31+ setConnected (true );
32+ console .log (' Connected: ' + frame);
33+ stompClient .subscribe (' /topic/message' , function (messageOutput ) {
34+ showMessageOutput (JSON .parse (messageOutput .body ));
35+ });
36+ });
37+ }
38+
39+ function disconnect () {
40+
41+ if (stompClient != null ) {
42+ stompClient .disconnect ();
43+ }
44+
45+ setConnected (false );
46+ console .log (" Disconnected" );
47+ }
48+
49+ function sendMessage () {
50+
51+ var text = document .getElementById (' text' ).value ;
52+ stompClient .send (" /app/chat" , {}, JSON .stringify ({ ' text' : text }));
53+ }
54+
55+ function showMessageOutput (messageOutput ) {
56+
57+ var response = document .getElementById (' response' );
58+ var p = document .createElement (' p' );
59+ p .style .wordWrap = ' break-word' ;
60+ p .appendChild (document .createTextNode (messageOutput .time + " : " + messageOutput .text ));
61+ response .appendChild (p);
62+ }
63+
64+ </script >
65+
66+ </head >
67+
68+ <body onload =" disconnect()" >
69+
70+ <div >
71+ <div >
72+ <button id =" connect" onclick =" connect();" >Connect</button >
73+ <button id =" disconnect" disabled =" disabled" onclick =" disconnect();" >Disconnect</button >
74+ </div >
75+ <br />
76+ <div id =" conversationDiv" >
77+ <input type =" text" id =" text" placeholder =" Write a message..." />
78+ <button id =" sendMessage" onclick =" sendMessage();" >Send</button >
79+ <p id =" response" ></p >
80+ </div >
81+ </div >
82+
83+ </body >
84+ </html >
0 commit comments