Browse Source

spring-boot-demo-websocket-socketio 前端完成

pull/1/head
Yangkai.Shen 6 years ago
parent
commit
2e34b5282b
8 changed files with 5221 additions and 10 deletions
  1. +2
    -1
      spring-boot-demo-websocket-socketio/src/main/java/com/xkcoding/websocket/socketio/controller/MessageController.java
  2. +11
    -9
      spring-boot-demo-websocket-socketio/src/main/java/com/xkcoding/websocket/socketio/handler/MessageEventHandler.java
  3. +29
    -0
      spring-boot-demo-websocket-socketio/src/main/java/com/xkcoding/websocket/socketio/payload/JoinRequest.java
  4. +4983
    -0
      spring-boot-demo-websocket-socketio/src/main/resources/static/bootstrap.css
  5. +181
    -0
      spring-boot-demo-websocket-socketio/src/main/resources/static/index.html
  6. +6
    -0
      spring-boot-demo-websocket-socketio/src/main/resources/static/js/jquery-1.10.1.min.js
  7. +6
    -0
      spring-boot-demo-websocket-socketio/src/main/resources/static/js/moment.min.js
  8. +3
    -0
      spring-boot-demo-websocket-socketio/src/main/resources/static/js/socket.io/socket.io.js

+ 2
- 1
spring-boot-demo-websocket-socketio/src/main/java/com/xkcoding/websocket/socketio/controller/MessageController.java View File

@@ -8,6 +8,7 @@ import com.xkcoding.websocket.socketio.payload.BroadcastMessageRequest;
import lombok.extern.slf4j.Slf4j; import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping; import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController; import org.springframework.web.bind.annotation.RestController;


@@ -34,7 +35,7 @@ public class MessageController {
private MessageEventHandler messageHandler; private MessageEventHandler messageHandler;


@PostMapping("/broadcast") @PostMapping("/broadcast")
public Dict broadcast(BroadcastMessageRequest message) {
public Dict broadcast(@RequestBody BroadcastMessageRequest message) {
if (isBlank(message)) { if (isBlank(message)) {
return Dict.create().set("flag", false).set("code", 400).set("message", "参数为空"); return Dict.create().set("flag", false).set("code", 400).set("message", "参数为空");
} }


+ 11
- 9
spring-boot-demo-websocket-socketio/src/main/java/com/xkcoding/websocket/socketio/handler/MessageEventHandler.java View File

@@ -10,6 +10,7 @@ import com.xkcoding.websocket.socketio.config.DbTemplate;
import com.xkcoding.websocket.socketio.config.Event; import com.xkcoding.websocket.socketio.config.Event;
import com.xkcoding.websocket.socketio.payload.BroadcastMessageRequest; import com.xkcoding.websocket.socketio.payload.BroadcastMessageRequest;
import com.xkcoding.websocket.socketio.payload.GroupMessageRequest; import com.xkcoding.websocket.socketio.payload.GroupMessageRequest;
import com.xkcoding.websocket.socketio.payload.JoinRequest;
import com.xkcoding.websocket.socketio.payload.SingleMessageRequest; import com.xkcoding.websocket.socketio.payload.SingleMessageRequest;
import lombok.extern.slf4j.Slf4j; import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Autowired;
@@ -86,14 +87,14 @@ public class MessageEventHandler {
* *
* @param client 客户端 * @param client 客户端
* @param request 请求 * @param request 请求
* @param roomId 群聊
* @param data 群聊
*/ */
@OnEvent(value = Event.JOIN) @OnEvent(value = Event.JOIN)
public void onJoinEvent(SocketIOClient client, AckRequest request, String roomId) {
// 模拟用户id 和token一致
String userId = client.getHandshakeData().getSingleUrlParam("token");
log.info("用户:{} 已加入群聊:{}", userId, roomId);
client.joinRoom(roomId);
public void onJoinEvent(SocketIOClient client, AckRequest request, JoinRequest data) {
log.info("用户:{} 已加入群聊:{}", data.getUserId(), data.getGroupId());
client.joinRoom(data.getGroupId());
server.getRoomOperations(data.getGroupId()).sendEvent(Event.JOIN, data);
} }




@@ -103,12 +104,13 @@ public class MessageEventHandler {
if (toUser.isPresent()) { if (toUser.isPresent()) {
log.info("用户 {} 刚刚私信了用户 {}:{}", data.getFromUid(), data.getToUid(), data.getMessage()); log.info("用户 {} 刚刚私信了用户 {}:{}", data.getFromUid(), data.getToUid(), data.getMessage());
sendToSingle(toUser.get(), data); sendToSingle(toUser.get(), data);
client.sendEvent(Event.CHAT_RECEIVED, "发送成功");
} else { } else {
client.sendEvent(Event.CHAT_REFUSED, "对方不在线");
client.sendEvent(Event.CHAT_REFUSED, "发送失败,对方不想理你");
} }
} }


@OnEvent(value = Event.CHAT)
@OnEvent(value = Event.GROUP)
public void onGroupEvent(SocketIOClient client, AckRequest request, GroupMessageRequest data) { public void onGroupEvent(SocketIOClient client, AckRequest request, GroupMessageRequest data) {
log.info("群号 {} 收到来自 {} 的群聊消息:{}", data.getGroupId(), data.getFromUid(), data.getMessage()); log.info("群号 {} 收到来自 {} 的群聊消息:{}", data.getGroupId(), data.getFromUid(), data.getMessage());
sendToGroup(data); sendToGroup(data);
@@ -118,7 +120,7 @@ public class MessageEventHandler {
* 单聊 * 单聊
*/ */
public void sendToSingle(UUID sessionId, SingleMessageRequest message) { public void sendToSingle(UUID sessionId, SingleMessageRequest message) {
server.getClient(sessionId).sendEvent(Event.CHAT_RECEIVED, message);
server.getClient(sessionId).sendEvent(Event.CHAT, message);
} }


/** /**


+ 29
- 0
spring-boot-demo-websocket-socketio/src/main/java/com/xkcoding/websocket/socketio/payload/JoinRequest.java View File

@@ -0,0 +1,29 @@
package com.xkcoding.websocket.socketio.payload;

import lombok.Data;

/**
* <p>
* 加群载荷
* </p>
*
* @package: com.xkcoding.websocket.socketio.payload
* @description: 加群载荷
* @author: yangkai.shen
* @date: Created in 2018-12-19 13:36
* @copyright: Copyright (c) 2018
* @version: V1.0
* @modified: yangkai.shen
*/
@Data
public class JoinRequest {
/**
* 用户id
*/
private String userId;

/**
* 群名称
*/
private String groupId;
}

+ 4983
- 0
spring-boot-demo-websocket-socketio/src/main/resources/static/bootstrap.css
File diff suppressed because it is too large
View File


+ 181
- 0
spring-boot-demo-websocket-socketio/src/main/resources/static/index.html View File

@@ -0,0 +1,181 @@
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8"/>
<title>spring-boot-demo-websocket-socketio</title>
<link href="bootstrap.css" rel="stylesheet">
<link href="https://cdn.bootcss.com/layer/2.3/skin/layer.css" rel="stylesheet">
<style>
body {
padding: 20px;
}

#console {
height: 400px;
overflow: auto;
}

.username-msg {
color: orange;
}

.connect-msg {
color: green;
}

.disconnect-msg {
color: red;
}

.broadcast {
color: red;
}

.send-msg {
color: #888
}

.sys-msg {
color: #888
}

</style>

<script src="js/socket.io/socket.io.js"></script>
<script src="js/moment.min.js"></script>
<script src="js/jquery-1.10.1.min.js"></script>
<script src="https://cdn.bootcss.com/axios/0.19.0-beta.1/axios.min.js"></script>
<script src="https://cdn.bootcss.com/layer/2.3/layer.js"></script>
<script>
const token = 'user' + Math.floor((Math.random() * 1000) + 1);
const url = `http://127.0.0.1:8081?token=${token}`;
const socket = io.connect(url);
socket.on('connect', function () {
output(`<span class="connect-msg">系统通知: ${token}成功连接至websocket服务器</span>`);
});

socket.on('join', function (data) {
output(`<span class="sys-msg">${data.groupId} 群通知: 新人 ${data.userId} 请爆照</span>`);
});

socket.on('chat', function (data) {
output(`<span class="username-msg">系统通知: 收到来自 ${data.fromUid} 的悄悄话: ${data.message}</span>`);
});

socket.on('chat_received', function (data) {
output(`<span class="username-msg">系统通知: 悄悄话, ${data}</span>`);
});

socket.on('chat_refused', function (data) {
output(`<span class="username-msg">系统通知: 悄悄话, ${data}</span>`);
});

socket.on('group', function (data) {
output(`<span class="username-msg">${data.groupId} 群消息: ${data.fromUid} 说: ${data.message}</span>`);
});

socket.on('disconnect', function () {
output(`<span class="disconnect-msg">系统通知: ${token}已从websocket服务器断开连接</span>`);
});

socket.on('broadcast', function (data) {
output(`<span class="broadcast">${data.message}</span>`);
});

function sendConnect() {
socket.connect();
}

function sendDisconnect() {
socket.disconnect();
}

function sendBroadcast() {
axios.post('/demo/send/broadcast', {
message: '系统广播通知: 当前时间 ' + moment().format('YYYY-MM-dd HH:mm:ss.SSS')
}).then((response) => {
const {flag, message} = response.data;
if (flag) {
layer.msg(message, {icon: 6});
} else {
layer.msg(message, {icon: 5});
}
});
}

function sendJoin() {
let joinRequest = {
userId: token,
groupId: "666"

};
socket.emit('join', joinRequest);
}

function sendMessage() {
let message = $('#msg').val();

if (message === '') {
layer.msg('你不说点什么嘛?', {icon: 5});
return;
}

$('#msg').val('');
let groupRequest = {
fromUid: token,
groupId: "666",
message: message
};
socket.emit('group', groupRequest);
}

function sendChat() {
let toUserId = $('#to').val();
let message = $('#msg').val();

if (toUserId === '') {
layer.msg('请输入对方昵称', {icon: 5});
return;
}
if (message === '') {
layer.msg('你不说点什么嘛?', {icon: 5});
return;
}
$('#to').val('');
$('#msg').val('');

let singleRequest = {
fromUid: token,
toUid: toUserId,
message: message
};
socket.emit('chat', singleRequest, function () {
output(`<span class="username-msg">系统通知: 你刚刚和 ${singleRequest.toUid} 说了句悄悄话</span>`);
});
}

function output(message) {
let currentTime = "<span class='time'>" + moment().format('YYYY-MM-dd HH:mm:ss.SSS') + "</span>";
let element = $("<div>" + currentTime + " " + message + "</div>");
$('#console').prepend(element);
}

</script>
</head>
<body>
<h1>spring-boot-demo-websocket-socketio</h1>
<br/>
<div id="console" class="well">
</div>
<form class="well form-inline" onsubmit="return false;">
<input id="msg" class="input-xlarge" type="text" placeholder="随便输点啥"/>
<input id="to" class="input-xlarge" type="text" placeholder="私聊发给谁"/>
<button type="button" onClick="sendJoin()" class="btn" id="join">加入群聊</button>
<button type="button" onClick="sendMessage()" class="btn" id="send">群聊</button>
<button type="button" onClick="sendChat()" class="btn" id="chat">私聊</button>
<button type="button" onClick="sendBroadcast()" class="btn">广播消息</button>
<button type="button" onClick="sendConnect()" class="btn">连接</button>
<button type="button" onClick="sendDisconnect()" class="btn">断开</button>
</form>
</body>
</html>

+ 6
- 0
spring-boot-demo-websocket-socketio/src/main/resources/static/js/jquery-1.10.1.min.js
File diff suppressed because it is too large
View File


+ 6
- 0
spring-boot-demo-websocket-socketio/src/main/resources/static/js/moment.min.js
File diff suppressed because it is too large
View File


+ 3
- 0
spring-boot-demo-websocket-socketio/src/main/resources/static/js/socket.io/socket.io.js
File diff suppressed because it is too large
View File


Loading…
Cancel
Save