SpringMvc + socket.io + vue + vue-socket.io實例
<dependency> <groupId>com.corundumstudio.socketio</groupId> <artifactId>netty-socketio</artifactId> <version>1.7.7</version> </dependency>
其他相關依賴
<dependency> <groupId>com.fasterxml.jackson.core</groupId> <artifactId>jackson-core</artifactId> <version>2.9.6</version> </dependency> <dependency> <groupId>org.slf4j</groupId> <artifactId>slf4j-api</artifactId> <version>${slf4j.version}</version> </dependency> <dependency> <groupId>org.slf4j</groupId> <artifactId>log4j-over-slf4j</artifactId> <version>${slf4j.version}</version> </dependency>
2. 服務端類實現 (SocketIO.java)
import java.util.Map; import org.springframework.context.ApplicationListener;import org.springframework.context.event.ContextRefreshedEvent; import org.springframework.stereotype.Component; import com.corundumstudio.socketio.AckRequest; import com.corundumstudio.socketio.Configuration; import com.corundumstudio.socketio.SocketIOClient; import com.corundumstudio.socketio.SocketIOServer; import com.corundumstudio.socketio.listener.ConnectListener; import com.corundumstudio.socketio.listener.DataListener; import com.corundumstudio.socketio.listener.DisconnectListener; @Component("socketIO") public class SocketIO implements ApplicationListener<ContextRefreshedEvent> { public void onApplicationEvent(ContextRefreshedEvent arg0) { new Thread(new Runnable() { public void run() { // TODO Auto-generated method stub socketStart(); } }).start(); } private void socketStart() { System.out.println("in socketio"); // TODO Auto-generated method stub Configuration config = new Configuration(); config.setHostname("127.0.0.1"); config.setPort(9092); config.setMaxFramePayloadLength(1024 * 1024); config.setMaxHttpContentLength(1024 * 1024); SocketIOServer server = new SocketIOServer(config); server.addConnectListener(new ConnectListener() { public void onConnect(SocketIOClient client) { // TODO Auto-generated method stub String clientInfo = client.getRemoteAddress().toString(); String clientIp = clientInfo.substring(1,clientInfo.indexOf(":"));//獲取ip client.sendEvent("cliented", "ip: " + clientIp); } }); server.addDisconnectListener(new DisconnectListener() { public void onDisconnect(SocketIOClient client) { String clientInfo = client.getRemoteAddress().toString(); String clientIp = clientInfo.substring(1,clientInfo.indexOf(":"));//獲取ip client.sendEvent("disconned", "ip: " + clientIp); } }); server.addEventListener("msginfo", String.class, new DataListener<String>() { public void onData(SocketIOClient client, String data, AckRequest arg2) throws Exception { // TODO Auto-generated method stub String clientInfo = client.getRemoteAddress().toString(); String clientIp = clientInfo.substring(1, clientInfo.indexOf(":")); System.out.println(clientIp+":客戶端:************"+data); client.sendEvent("msginfo", "服務端返回信息!"); } }); server.start(); try { Thread.sleep(Integer.MAX_VALUE) ; } catch (InterruptedException e) { // TODO Auto-generated catch block e.printStackTrace(); } server.stop(); } }
將該類添加到 xml 配置文件,讓它容器啟動後執行;
<bean id="socketIO" class="com.spring.getinfo.utils.SocketIO"></bean>
運行 springmvc
vue端實現
1. vue 環境安裝;
a. 安裝node.js(https://nodejs.org/en/)
選擇 Current
b. 設置相關參數: (NODE_HOME, PATH等)
c. 安裝 cnpm
npm install -g cnpm --registry=https://registry.npm.taobao.org
d. 安裝 vue
cnpm install vue -g
e. vue-cli 腳手架
cnpm install vue-cli -g
2. 創建 vue 項目
vue init webpack-simple vueProj
>cd vueProj 進入 vueProj項目目錄
>cnpm install 生成 node_modules 等相關目錄及文件
3. 引入 vue-socket.io
npm install vue-socket.io --save
使用 /src/main.js
import VueSocketio from ‘vue-socket.io‘ Vue.use(new VueSocketio({ debug: true, connection: ‘http://localhost:9092‘ }));
在 /src/App.vue
<div> <input type="text" name="box" ref="box" /> <input type="button" @click="clickButton(‘user1‘)" value="button" /> </div>
以及 腳本
export default { name: ‘app‘, data () { return { msg: ‘Welcome to Your Vue.js App‘ } }, sockets: { connect: function () { console.log(‘socket connected‘); //this.$socket.emit(‘login‘, ‘socket connectedxxxx‘); }, msginfo: function (data) { //console.log(‘this method was fired by the socket server. eg: io.emit("customEmit", data)‘); console.log("client: " + data); }, }, methods: { clickButton: function () { var msg = this.$refs.box.value; console.log(msg); this.$socket.emit(‘msginfo‘, msg); } } }
使用 vue 運行端口 (項目目錄 vueProj/package.json,添加紅色部分)
"scripts": { "dev": "cross-env NODE_ENV=development webpack-dev-server --open --hot --port 9192", "build": "cross-env NODE_ENV=production webpack --progress --hide-modules" },
然後運行vue項目,在vueProj目錄下(cmd窗口),執行 cnpm run dev;
scripts 下 connect是內置事件 (偵聽連接服務端成功);msginfo為自定義事件,與 this.$socket.emit(‘msginfo‘, xxxxx) 對應;
截圖:
窗口1:
窗口2:
服務端截圖:
SpringMvc + socket.io + vue + vue-socket.io實例