Artikel ini berbagi dengan Anda SpringMVC terintegrasi Websocket untuk mengimplementasikan Push Push untuk referensi Anda. Konten spesifiknya adalah sebagai berikut
1. Buat latar belakang untuk protokol jabat tangan WebSocket
(1) Kelas Implementasi Jabat tangan
/** *Nama Proyek: Harga *Nama File: Handshake.java *Nama Paket: com.yun.websocket *Tanggal: 3 September 2016 jam 4:44:27 PM *Hak cipta (c) [email protected] Semua hak dilindungi undang -undang. */ paket com.yun.websocket; impor java.util.map; impor org.springframework.http.server.serverHttpRequest; impor org.springframework.http.server.serverhttpresponse; impor org.springframework.http.server.servletserverHttpRequest; impor org.springframework.web.socket.websockethandler; impor org.springframework.web.socket.server.handshakeInterceptor; /** *Title: HandShake<br/> *Description: *@Company: Qingdao Litu Hi-Tech<br/> *@author: Liu Yunsheng*@version: v1.0 *@since: JDK 1.7.0_80 *@Date: September 3, 2016 at 4:44:27 pm <br/> */ public class HandShake implements HandshakeInterceptor{ @Override public boolean Sebelum Handshake (Permintaan ServerHttPRequest, ServerHttPresponse Response, WebSockethandler Wshandler, Map <String, Object> Atribut) Melemparkan Exception {// TODO Metode yang dihasilkan secara otomatis. // Tag user // string userid = (string) session.getAttribute ("userId"); if (jspcode! = null) {attributes.put ("jspcode", jspcode); } else {return false; } return true; } @Override public void afterhandshake (serverHttpRequest request, serverHttpresponse response, WebSockethandler wshandler, pengecualian pengecualian) {// TODO Metode yang dihasilkan secara otomatis Stub}}
(2) kelas implementasi mywebsocketconfig
/** *Nama Proyek: Harga *Nama File: MyWebsocketConfig.java *Nama Paket: com.yun.websocket *Tanggal: 3 September 2016 jam 4:52:29 PM *Hak cipta (c) [email protected] Semua hak dilindungi undang -undang. */ paket com.yun.websocket; impor javax.annotation.Resource; impor org.springframework.stereotype.component; impor org.springframework.web.servlet.config.annotation.enableWebmvc; impor org.springframework.web.servlet.config.annotation.webmvccconfigurerAdapter; impor org.springframework.web.socket.config.annotation.enableWebsocket; impor org.springframework.web.socket.config.annotation.websocketConfigurer; impor org.springframework.web.socket.config.annotation.websockethandlerregistry; /** *Judul: mywebsocketConfig <br/> *Deskripsi: *@Perusahaan: Qingdao Litu Hi-Tech <br/> *@Author: Liu Yunsheng *@Versi: V1.0 *@Sejak: JDK 1.7.0_80 *Tanggal: 3 September 2016 AT 4:52:29 pm <brpon/@combone@publon@26 September di 4:52:29 pm. MywebsocketConfig memperluas WebMvCconfigurerAdapter mengimplementasikan WebSocketConfigurer {@resource mywebsockethandler handler; @Override public void registerwebsockethandlers (WebSockethandlerRegistry registry) {// TODO Metode yang dihasilkan secara otomatis Stub registry.addhandler (Handler, "/wsmy").addinterceptors(new handshake ()); registry.addhandler (pawang, "/wsmy/sockjs").addInterceptors(new handshake ()). withsockjs (); }}
(3) Kelas Implementasi MyWebsockethandler
/** *Nama Proyek: Harga *Nama File: MyWebsockethandler.java *Nama Paket: com.yun.websocket *Tanggal: 3 September 2016 jam 4:55:12 PM *Hak cipta (c) [email protected] Semua hak dilindungi undang -undang. */ paket com.yun.websocket; impor java.io.ioException; impor java.util.hashmap; impor java.util.iterator; impor java.util.map; impor java.util.map.entry; impor org.springframework.stereotype.component; impor org.springframework.web.socket.closestatus; impor org.springframework.web.socket.textmessage; impor org.springframework.web.socket.websockethandler; impor org.springframework.web.socket.websocketmessage; impor org.springframework.web.socket.websocketsession; impor com.google.gson.gsonbuilder; /** *Judul: mywebsockethandler <br/> *Deskripsi: *@Company: Qingdao Litu Hi-Tech <br/> *@Author: Liu Yunsheng *@Versi: v1.0 *@Sejak: JDK 1.7.0_80 *@Tanggal: September 2016 at 4:55:12 pm <br/>/@competlone publoning myweone myweoning myweoning myweoning myweoning myweeton myweeton myweetoning myweeton myweeton myweetoning myweeton myweeten myweeton mywe my websller {@compethon@@class publicon: peta akhir <string, WebSocketSession> userocketsessionMap; static {UsersocketSessionMap = new HashMap <String, WebSocketSession> (); } @Override public void afterconnectionestablished (Sesi WebSocketsession) melempar Exception {// TODO Metode yang dihasilkan secara otomatis string string jspcode = (string) session.getHandShakeattributes (). Get ("jspcode"); if (UsersocketSessionMap.get (jspcode) == null) {userocketsessionMap.put (jspcode, session); } untuk (int i = 0; i <10; i ++) {// siaran (TextMessage baru (GsonBuilder baru (). Create (). TOJSON ("/" Nomor/":/"+i+"/")); sesi. Gsonbuilder (). Create (). Tojson ("/" number/":/"+i+"/" "))); }} @Override public void handlemessage (Sesi WebSocketsession, WebSocketMessage <?> Message) melempar Exception {// TODO Metode yang dihasilkan secara otomatis Stub // pesan msg = baru gson (). Fromjson (message.getPayload (). Tostring (), pesan.class); //msg.setDate( tanggal baru ()); // sendMessageTouser (msg.getto (), TextMessage baru (GsonBuilder baru (). setDateFormat ("yyyy-mm-dd hh: mm: ss"). create (). Tojson (msg))); session.sendMessage (pesan); } @Override public void handletransporterror (Sesi WebSocketsession, Throwable Exception) melempar Exception {// TODO METODE AUTO-ENTO-METODE Stub if (session.isopen ()) {session.close (); } Iterator <entry <string, WebSocketSession >> it = userocketsessionMap .Entryset (). Iterator (); // Hapus sesi soket while (it.hasnext ()) {entri <string, WebSocketSession> entri = it.next (); if (entry.getValue (). getId (). Equals (session.getId ())) {UsersocketSessionMap.remove (entry.getKey ()); System.out.println ("Soket Sesi telah dihapus: ID Pengguna" + Entry.getKey ()); merusak; }}} @Override public void afterconnectionclosed (Sesi WebSocketsession, Closestatus Closestatus) melempar Exception {// TODO Metode Stub System.out.out.println ("WebSocket:" + Sesion.getid () + "Tutup"); Iterator <entry <string, WebSocketSession >> it = userocketsessionMap .Entryset (). Iterator (); // Hapus sesi soket while (it.hasnext ()) {entri <string, WebSocketSession> entri = it.next (); if (entry.getValue (). getId (). Equals (session.getId ())) {UsersocketSessionMap.remove (entry.getKey ()); System.out.println ("Soket Sesi telah dihapus: ID Pengguna" + Entry.getKey ()); merusak; }}} @Override Public Boolean SupportSpartialMessages () {// TODO Metode yang dihasilkan secara otomatis Stub Return return false; } / ** * Bulk * @Title: siaran * @description: TODO * @param: @param pesan * @param: @throws IoException * @return: void * @author: Liu yunsheng * @Date: 4:23:30 pada 10 September 2016 * @Throws * / public void siaran public (4:23:30 pm) pada 10 September 2016 * @THROWS * / PUBLIC VOID PUBLIK (PUBLOPER (4:23 PMS) pada 10 September 2016 * @THROWS / PUBLIK PUBLOK (PUBROURE (PUBROGE (PUTROPEON (PUTROPEON (PUTROPEON 2016 WebSocketSession >> it = UsersocketSessionMap .Entryset (). Iterator (); // Multithreading mass Sending whene (it.hasnext ()) {entri akhir <string, WebSocketsession> entri = it.next (); if (entry.getValue (). isopen ()) {thread baru (runnable baru () {public void run () {coba {if (entry.getValue (). isopen ()) {entry.getValue (). SendMessage (pesan);}} catch (ioException e) {e.print.). }}}} / ** * Kirim pesan ke halaman inspeksi rekayasa waktu-nyata dari semua pengguna online * * @param pesan * @throws ioException * / public void sendMessageTojsp (webseMessage final, tipe string) lemparan ioException {iterator <entry <string, websocketsession >> iterercession. // pengiriman massal multithreaded whene (it.hasnext ()) {entri akhir <string, WebSocketsession> entri = it.next (); if (entry.getValue (). isOpen () && entry.getKey (). contains (type)) {thread baru (runnable baru () {public void run () {coba {if (entry.getValue ().} {everccepion {chetscepion (). } }).awal(); }}}}}}
2. Buat meja depan untuk pemrosesan jabat tangan WebSocket
<script> var path = '<%= Basepath%>'; var userid = 'lys'; if (userId ==-1) {window.location.href = "<%= BasePath2%>" rel = "nofollow eksternal"; } var jspcode = userid+"_ aaa"; var Websocket; if ('WebSocket' di jendela) {WebSocket = WebSocket baru ("ws: //" + path + "wsmy? jspcode =" + jspcode); } lain jika ('mozwebsocket' di jendela) {websocket = mozwebsocket baru ("ws: //" + path + "wsmy? jspcode =" + jspcode); } else {websocket = sockjs baru ("http: //" + path + "wsmy/sockjs? jspcode =" + jspcode); } websocket.onopen = function (event) {console.log ("WebSocket: Connected"); Console.log (acara); }; websocket.onMessage = function (event) {var data = json.parse (event.data); console.log ("WebSocket: menerima pesan -norm", data); alert ("Websocket: menerima pesan"); }; websocket.onerror = function (event) {console.log ("WebSocket: kesalahan terjadi"); Console.log (acara); }; websocket.onclose = function (event) {console.log ("WebSocket: tutup"); Console.log (acara); } </script>3. Latar Belakang Websocket Push melalui panggilan pengontrol
/** *Nama Proyek: Harga *Nama File: Garlicpricecontroller.java *Nama Paket: com.yun.price.garlic.controller *Tanggal: 23 Juni 2016 di 3:23:46 PM *Hak Cipta (c) [email protected] Semua Hak Dilaga. */ paket com.yun.price.garlic.controller; impor java.io.ioException; impor java.util.date; impor java.util.list; impor javax.annotation.Resource; impor javax.servlet.http.httpservletRequest; impor javax.servlet.http.httpsession; impor org.springframework.beans.factory.annotation.Autowired; impor org.springframework.stereotype.controller; impor org.springframework.web.bind.annotation.requestmapping; impor org.springframework.web.bind.annotation.requestmethod; impor org.springframework.web.bind.annotation.responseBody; impor org.springframework.web.context.request.requestcontextholder; impor org.springframework.web.context.request.servletrequestattributes; impor org.springframework.web.servlet.modelandview; impor org.springframework.web.socket.textmessage; impor com.google.gson.gsonbuilder; impor com.yun.common.entity.datagrid; impor com.yun.price.garlic.dao.entity.garlicprice; impor com.yun.price.garlic.model.garlicpricemodel; impor com.yun.price.garlic.service.garlicpriceservice; impor com.yun.websocket.mywebsockethandler; /** * Judul: GarlicPriceController <br/> * Deskripsi: * * @company: Qingdao litu hi-tech <br/> * @author: liu yunsheng * @version: v1.0 * @since: jdk 1.7.0_80 * @date: 23 Juni 2016 at 3:23: Jdk 1.7.0_80 * @date: 23 Juni 2016 at 3:23:2 GarlicPriceController {@resource mywebsockethandler mywebsockethandler; @RequestMapping (value = "GarlicPriceController/TestWebsocket", Method = {RequestMethod.post, RequestMethod.get}, menghasilkan = "Application/JSON; Charset = UTF-8") @ResponseBody String public testwebsocket () lemparan ioException {myWerbsockybody Public testwebsocket () lemparan ioException {myweScockhy PublicBody Gsonbuilder (). Create (). TOJSON ("/" NUMBER/":/"+"GARLICPRICECONTROLLER/TESTWEBSOCKET"+"/" ")," AAA "); return" 1 ";}}
4. Paket JAR yang digunakan
<dependency> <GroupId> org.springframework </groupid> <ArTifactId> Spring-Websocket </artifactid> <version> 4.0.1.release </versi> </dependency>
5. Lingkungan Operasi
Setidaknya tomcat8.0 atau lebih, jika tidak, kesalahan dapat dilaporkan
Di atas adalah semua konten artikel ini. Saya berharap ini akan membantu untuk pembelajaran semua orang dan saya harap semua orang akan lebih mendukung wulin.com.