SpringMvc + socket.io + vue + vue-socket.io实例

时间:2023-03-10 03:46:15
SpringMvc + socket.io + vue + vue-socket.io实例
SpringMvc部分实现
 1. 所需依赖
<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:

SpringMvc + socket.io + vue + vue-socket.io实例

窗口2:

SpringMvc + socket.io + vue + vue-socket.io实例

服务端截图:

SpringMvc + socket.io + vue + vue-socket.io实例