1. 程式人生 > >spring建立websocket例子

spring建立websocket例子

1、依賴包
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-websocket</artifactId>
<version>${org.springframework-version}</version>
</dependency>
2、配置檔案
<context:component-scan base-package="com.jrj.springwebsocket" />
<websocket:handlers>
<websocket:mapping handler="webSocketHandler" path="/websocket"/>
<websocket:sockjs />
</websocket:handlers>
<bean id="webSocketHandler" class="com.jrj.springwebsocket.WebSocketHandler" />
3、前端js建立連線
<script type="text/javascript">
var websocket = null;
/* if('WebSocket' in window) {
websocket = new WebSocket("ws://localhost:8080/springwebsocket/websocket");
} else {
alert('當前瀏覽器不支援websocket!');
websocket = new SockJS("http://localhost:8080/springwebsocket/websocket");
} */
websocket = new SockJS("http://localhost:8080/springwebsocket/websocket");

websocket.onerror = function() {
setMessage("websocket連接出錯");
}

websocket.onopen= function() {
 setMessage("websocket連線成功!");}websocket.onmessage= function(event) {setMessage(event.data);}websocket.onclose= function() {close();}function setMessage(text) {$("#message").append(text).append("<br>");}function close() {websocket.close();}function send() {var msg = $("#text").val();websocket.send(msg);}</script>
4、後端連線類
package com.jrj.springwebsocket;


import org.springframework.web.socket.CloseStatus;
import org.springframework.web.socket.TextMessage;
import org.springframework.web.socket.WebSocketSession;
import org.springframework.web.socket.handler.AbstractWebSocketHandler;


public class WebSocketHandler extends AbstractWebSocketHandler {


private WebSocketSession session;
@Override
public void afterConnectionClosed(WebSocketSession session, CloseStatus status) throws Exception {
// TODO Auto-generated method stub
super.afterConnectionClosed(session, status);
System.out.println("a new connection incoming...");
}


@Override
public void afterConnectionEstablished(WebSocketSession session) throws Exception {
// TODO Auto-generated method stub
super.afterConnectionEstablished(session);
System.out.println("a new connection exiting...");
}


@Override
protected void handleTextMessage(WebSocketSession session, TextMessage message) throws Exception {
String payload = message.getPayload();
System.out.println("server received:" + payload);
this.session=session;
session.sendMessage(new TextMessage(payload));
}
protected void handleTextMessage(String message) throws Exception {
System.out.println("server received:" + message);
this.session.sendMessage(new TextMessage(message));
}


}


5、後端推送類
package com.jrj.springwebsocket;


import java.text.DateFormat;
import java.util.Date;
import java.util.Locale;


import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
@Controller
public class PushController {
@Autowired
private WebSocketHandler webSocketHandler;
@RequestMapping(value = "/push", method = RequestMethod.GET)
public void home(Locale locale, Model model) throws Exception {
while(true) {
Date date = new Date();
webSocketHandler.handleTextMessage("push message:" + date.getTime());
Thread.sleep(1000);
}
}
}
6、結果演示



7、git程式碼地址
https://github.com/xf87/springwebsocket 

相關推薦

spring建立websocket例子

1、依賴包 <dependency><groupId>org.springframework</groupId><artifactId>spring-websocket</artifactId><versio

使用 Spring Boot WebSocket 建立聊天室

1    第2-10課:使用Spring Boot WebSocket建立聊天室 1.1.1       什麼是 WebSocket 以前,很多網站為了實現推送技術,所用的技術都是輪詢。輪詢是在特定的的時間間隔(如每

Spring Websocket例子

基本概念 WebSocket協議提供了通過一個套接字實現全雙工通訊的功能。它能夠實現Web瀏覽器和伺服器之間的非同步通訊,全雙工意味著伺服器可以傳送訊息給瀏覽器,瀏覽器也可以傳送訊息給伺服器。Spring 4.0為WebSocket通訊提供了支援,主要是實現伺服器端和基於瀏

關於SpringWebSocket結合的簡單例子

      我的執行環境是:Tomcat 8.0 + Spring 4.0 + Myeclipse2014 + Firefox 42        JDK 1.8 不支援Spring 4.0 之前的版本       使用Google瀏覽器,Spring可能會丟擲異常:The

Spring boot——helloworld例子實現

and eba -exec odin url 工程目錄 cnblogs per simple 軟件152 緱旭浩 1.新建maven項目,package方式為war. 使用maven的時候,maven會從倉庫中下載依賴的jar包。 新建Maven Pr

Spring+Netty+WebSocket實例

adc random 目錄結構 div socket 相對 mage exec 客戶端 比較貼近生產,詳見註釋 一、pom.xml 具體太長,詳見源碼 </dependency> <dependency> &

springwebsocket的集成和使用

servlet ctype 基於 app set -c status att 實時通信 WebSocket是HTML5提出的一個用於通信的協議規範,該協議通過一個握手機制,在客戶端和服務端之間建立一個類似於TCP的連接,從而方便客戶端和服務端之間的通信。 WebSocket

mybatis 不整合spring 入門小例子

ole batis system [] commit print 管理 args private 先上一個搭建完的項目結構截圖: 相對比較重要的配置文件有 db.properties , SqlMappingConfig.xml , mapper/User.xm

Spring Boot 學習例子

base restfu lda tle sub spl over ber display 01.spring-boot-restfulservice 02.spring-boot-consumer 03.spring-boot-upload 04.spring-boot

zbb20180824 spring ioc aop 例子

nature release build index bean result method 控制 prope zbb_ioc_aop https://pan.baidu.com/disk/home#/all?vmode=list&path=%2Fcode%2

spring整合websocket通信

row final send 參考 cal utf-8 xtend art 文件 1. maven依賴 <?xml version="1.0" encoding="UTF-8"?> <project xmlns="http://maven.apache

Spring Chapter4 WebSocket 胡亂翻譯 (二)

標準 .html 丟失 perror 自動刪除 nco 整合 system 訂閱 書接上文,Spring Chapter4 WebSocket 胡亂翻譯 (一) 4.4.4. 消息流 一旦暴露了STOMP端點,Spring應用程序就成為連接客戶端的STOMP代理。 本節介紹

golang gorilla websocket例子

conn pack fault 客戶端 tdi mark scheme data package WebSocket協議是基於TCP的一種新的網絡協議。它實現了瀏覽器與服務器全雙工(full-duplex)通信——允許服務器主動發送信息給客戶端。 WebSocket通信協議

spring整合websocket js的編寫

  之前說了websocket的服務端編寫,下面說說客戶端的編寫,若要看服務端可以檢視連結:https://blog.csdn.net/jared_he2017/article/details/79886131 1.  首先通過服務端提供的websocket連線地址進行初始

資料庫的隔離級別以及併發問題(附spring+postgresql實際例子及解決方案)

參考資料 postgreSQL預設的隔離級別及修改 資料庫事務的四大特性以及事務的隔離級別 前言 在資料庫併發的事務中,可能產生的問題: 1,髒讀   髒讀是指在一個事務處理過程裡讀取了另一個未提交的事務中的資料。   當一個事務正在多次修改某個資料,而在這個

Spring Boot WebSocket 單節點模擬實現單點登入擠退

1、建立WebSocketServer @ServerEndpoint("/websocket/{sid}") @Component  // 成分、元件 public class WebSocketServer {     //靜態變數,用來記錄當前線上

Spring boot webSocket從入門到放棄

在構建Spring boot專案時已經提供webSocket依賴的勾選。webSocket是TCP之上的一個非常薄的輕量級層 ,webSocket主要的應用場景離不開即時通訊與訊息推送,但只要應用程式需要在瀏覽器和伺服器之間來回傳送訊息,就可以使用webSocket來降低客戶端流量與伺服器的負載。 下面將基

spring建立多例

最近遇到一個了問題,簡單的描述一下。 按模組呼叫介面,比如a、b、c、d四個模組每個模組2~3個介面,一筆交易最多四個模組,所以在呼叫時每個模組開啟一個執行緒。那麼問題來了模組執行緒在主執行緒中是通過註解自動注入的(模組執行緒依賴其他的bean,所以不能new),即模組執行緒單例的。 多

Spring-02 -Spring 建立物件的三種方式 :1.通過構造方法建立/2.例項工廠/3.靜態工廠

通過構造方法建立      1.1 無參構造建立:預設情況.     1.2 有參構造建立:需要明確配置       1.2.1 需要在類中提供有參構造方法       1.2.2 在 applicationContext.x

【swoole快速入門4】建立WebSocket伺服器

程式程式碼 ws_server.php //建立websocket伺服器物件,監聽0.0.0.0:9502埠 $ws = new swoole_websocket_server("0.0.0.0", 9502); //監聽WebSocket連線開啟事件 $ws->