springboot整合websocket(二)聊天室补充篇
springboot整合websocket(一)简单聊天室 springboot整合websocket(二)聊天室补充篇
springboot整合websocket(三)上传文件(引导篇) springboot整合websocket(四)上传文件(终篇)
这篇呢对上一篇聊天室做一个简单的补充,为下一篇文件上传做个铺垫
目标:
约定一个数据交换,对不同的字符串加以区分
为什么要这样呢?
因为我们的消息可能分很多种类型,比如说聊天、发送文件名给服务器(下一章会说到的)、或者其他业务需求的消息等等。
一、服务器端
1、引入fastjson(其他json解析包也可以)
这里我还用了lombok
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>fastjson</artifactId>
<version>1.2.76</version>
</dependency>
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
<optional>true</optional>
</dependency>
2、封装一个pojo
说明一下
- operation 是用来标识类型的
- msg 则是消息
@Data
@Builder
@NoArgsConstructor
@AllArgsConstructor
public class Message
{
private String operation;
private String msg;
public Message setOperation(String operation)
{
this.operation = operation;
return this;
}
public Message setMsg(String msg)
{
this.msg = msg;
return this;
}
}
3、修改OnMessage方法
说明一下
- 我这里去掉了OnOpen方法里面原有的东西
- tip 是用来进入聊天室后保存用户名
- msg是用来发送消息
@Log4j2
@Controller
@ServerEndpoint("/websocket")
public class BaseWebsocketController
{
@OnOpen
public void openSession(Session session, EndpointConfig config)
{
}
@OnMessage
public void onMessage(Session session, String message)
{
final Message data = JSONObject.parseObject(message, Message.class);
final Message response = Message.builder()
.operation(data.getOperation())
.build();
switch (data.getOperation()) {
case "tip":
session.getUserProperties().put("username", data.getMsg());
sessions.put(session.getId(), session);
response.setMsg("[" + data.getMsg() + "]进入房间");
sendAll(JSONObject.toJSONString(response));
break;
case "msg":
final String username = (String) session.getUserProperties().get("username");
response.setMsg("[" + username + "]" + data.getMsg());
sendAll(JSONObject.toJSONString(response));
break;
}
}
}
二、页面的改造
html不变,我这里就只放script的东西了
- 修改了 webSocket.onopen
- 修改了 webSocket.onMessage
- 修改了 $(’#sendBtn’).click()
- 添加了 function sendMessage(operation, msg){}
<script>
let webSocket;
let url = 'ws://127.0.0.1:8080/websocket';
$('#username').keyup(function (e) {
let keycode = e.which;
if (keycode == 13) {
$('#joinRoomBtn').click();
}
});
$('#joinRoomBtn').click(function () {
let username = $('#username').val();
webSocket = new WebSocket(url);
webSocket.onopen = function () {
console.log('webSocket连接创建。。。');
sendMessage('tip', username);
}
webSocket.onclose = function () {
console.log('webSocket已断开。。。');
$('#messageArea').append('websocket已断开\n');
}
webSocket.onmessage = function (event) {
let data = {
operation: '',
msg: ''
};
data = JSON.parse(event.data);
switch (data.operation){
case "tip":
$('#messageArea').append(data.msg + '\n');
break;
case "msg":
$('#messageArea').append(data.msg + '\n');
break;
}
}
webSocket.onerror = function (event) {
console.log(event)
console.log('webSocket连接异常。。。');
}
});
$('#leaveRoomBtn').click(function () {
if (webSocket) {
webSocket.close();
}
});
$('#sendBtn').click(function () {
var msg = $('#sendMessage').val();
if (msg.trim().length === 0) {
alert('请输入内容');
return;
}
sendMessage('msg', $('#sendMessage').val());
$('#sendMessage').val('');
});
function sendMessage(operation, msg) {
let data = {
operation: operation,
msg: msg,
};
webSocket.send(JSON.stringify(data));
}
</script>
End
springboot整合websocket(一)简单聊天室 springboot整合websocket(二)聊天室补充篇
springboot整合websocket(三)上传文件(引导篇) springboot整合websocket(四)上传文件(终篇)
|