一、创建Socket.io的服务端
官网写的已经非常详细了:https://socket.io/get-started/chat/
这里为了省事,直接晒代码了:
1、创建package.json
{
"name": "test_socketio",
"version": "1.0.0",
"description": "",
"main": "index.js",
"scripts": {
"test": "echo \"Error: no test specified\" && exit 1"
},
"keywords": [],
"author": "",
"license": "ISC",
"dependencies": {
"express": "^4.15.2",
"socket.io": "^2.3.0"
}
}
当然,我的项目名就叫test_socketio,大家可以随意命名。记得创建后npm install
2、创建index.html
这个是一个发送的调试界面,能够验证服务是否启动成功,页面代码来自官网的demo
Socket.IO chat
3、创建index.js
不说别的,直接上代码:
var app = require('express')();
var http = require('http').createServer(app);
var io = require('socket.io')(http);
app.get('/', (req, res) => {
res.sendFile(__dirname + '/index.html');
});
io.on('connection', (socket) => {
console.log('a user connected');
socket.on('disconnect', () => {
console.log('user disconnected');
});
socket.on('ServerIterationBroadcastSend', (data) => {
// INFO: Dechert: 2020/8/13 接收后端发来的广播推送请求
const dataObj = JSON.parse(data)
io.emit(`WebIterationBroadcastReceive`, dataObj.content) // INFO: Dechert: 2020/8/13 向web端发送从Java服务端收到的内容
})
socket.on('ServerIterationPointSend', (data) => {
// INFO: Dechert: 2020/8/13 接收后端发来的针对单一用户的推送请求
const dataObj = JSON.parse(data)
const userId = dataObj.userId
io.emit(`WebIterationPointReceive_${userId}`, dataObj.content) // INFO: Dechert: 2020/8/13 向web端发送从Java服务端收到的内容
})
});
io.emit('some event', {someProperty: 'some value', otherProperty: 'other value'}); // This will emit the event to all connected sockets
http.listen(3000, () => {
console.log('listening on *:3000');
});
注意:我这边后端的项目名叫ServerIteration,后端迭代项目,作为后端经验积累,不停更新迭代的项目框架类的项目。前端项目名叫WebIteration,作用和后端的差不多。由于这两个项目不便透露,我尽量描述的详细一点。
4、运行index.js
node index.js
这样SocketIO的服务端就运行在3000端口上了。
二、创建后端发送推送接口
1、创建一个发送推送内容的Service
@Slf4j
@Service
@Transactional
public class SocketIoSendService {
private static final String SERVER_NAME = "ServerIteration";
public MessageModel execute(SocketIoForm model) {
MessageModel messageModel = new MessageModel();
Integer sendType = model.getSendType();
String content = model.getContent();
Long userId = model.getUserId();
if (sendType == null) {
return messageModel.setFail("请选择发送类型");
}
if (StringUtils.isBlank(content)) {
return messageModel.setFail("请输入发送内容");
}
if (sendType == S_SocketIoSendType.POINT) {
if (userId == null) {
return messageModel.setFail("发送给指定用户,请输入用户ID");
}
}
try {
Socket socket = IO.socket("http://127.0.0.1:3000"); // INFO: Dechert: 2020/8/13 连接到SocketIO服务器
socket.connect();
AdvanceHashMap advanceHashMap = new AdvanceHashMap();
advanceHashMap.put("content", content);
if (sendType == S_SocketIoSendType.POINT) {
advanceHashMap.put("userId", model.getUserId());
socket.emit(SERVER_NAME + "PointSend", JSON.toJSONString(advanceHashMap));
} else {
socket.emit(SERVER_NAME + "BroadcastSend", JSON.toJSONString(advanceHashMap));
}
} catch (URISyntaxException e) {
e.printStackTrace();
}
messageModel.setSuccess();
return messageModel;
}
}
2、创建接口Controller
@Slf4j
@RestController
public class SaSocketIoSendController {
@Autowired
private SocketIoSendService service;
@RequestMapping(value = "/saSocketIoSend.sahtml", produces = "application/json;charset=UTF-8", method = {RequestMethod.GET, RequestMethod.POST})
public MessageModel execute(@RequestBody SocketIoForm model, HttpServletRequest request) {
MessageModel messageModel = service.execute(model);
return messageModel;
}
}
其中MessageModel和AdvanceHashMap都是继承自HashMap的,只是对于返回数据的简单封装罢了
三、创建Vue前端
使用vue-cli创建一个Vue项目,这点我不再赘述了,网上例子多得是
其中main.js
import Vue from 'vue'
import App from './App.vue'
import router from './router'
import ElementUi from "element-ui"
import VueSocketIo from 'vue-socket.io';
Vue.config.productionTip = false
Vue.use(ElementUi)
Vue.use(new VueSocketIo({
debug:true,
connection:'127.0.0.1:3000'
}))
new Vue({
router,
render: h => h(App),
}).$mount('#app')
SocketIo.vue
SocketIO
指定人员接收到的消息为:
{{receivePointMessage}}
广播消息为:
{{receiveBroadcastMessage}}
四、测试效果
想要测试效果,请使用Postman,采用POST请求,内容类型为json,浏览器中复制几个同样的页面。指定人员发送时,userId由于是随机的,请在F12的console中找到userId。