导入websocket的包。
通过使用SpringBoot导入包的时候,我们可以发现,很多包都是以 spring-boot-starter 开头的,对于我这种强迫症 ,简直是福音
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-websocket</artifactId>
</dependency>
配置websocket
服务端
首先新建一个WebSocketConfig的类,添加springboot中 @Bean 注解 注入一个bean
@Configuration
@EnableWebSocketMessageBroker
public class WebSocketConfig extends AbstractWebSocketMessageBrokerConfigurer {
private final static Logger logger = Logger.getLogger(WebSocketConfig.class);
public static List<User> onlineUsers = new ArrayList<User>();
public static List<GameRoom> gameRoomList = new ArrayList<GameRoom>();
@Autowired
private SimpMessagingTemplate simpMessagingTemplate;
@Override
public void registerStompEndpoints(StompEndpointRegistry stompEndpointRegistry) {
stompEndpointRegistry.addEndpoint("/endpointWisely").addInterceptors(new SessionAuthHandshakeInterceptor()).setHandshakeHandler(new DefaultHandshakeHandler() {
@Override
protected Principal determineUser(ServerHttpRequest request, WebSocketHandler wsHandler, Map<String, Object> attributes) {
User user = (User) attributes.get("user");
//System.out.println("新用户 : "+user.getUserName());
return new MyPrincipal(user);
}
}).withSockJS();
}
首先编写Controller层,@sentTo是做为客户端订阅发布的点
@MesseageMapping 是类似springmvc中@RequestMapping的访问地址
@Controller
public class WsController {
private final static Logger logger = Logger.getLogger(WsController.class);
private SimpMessagingTemplate messagingTemplate;
@MessageMapping(value="/welcome")
@SendTo("/topic/getResponse")
public WiselyResponse say(WebSocketSession session,WiselyMessage message) throws Exception{
return new WiselyResponse("welcome , "+message.getName()+" !");
}
@MessageMapping(value="/getOnlinePlayer")
@SendTo("/topic/getResponse")
public ResponseMessage getOnlinePlayer(Principal principal) throws Exception{
System.out.println(principal);
ResponseMessage responseMessage = new ResponseMessage();
JSONObject message = new JSONObject();
List<User> onlineUsers = WebSocketConfig.onlineUsers;
JSONArray usersJsonArray = new JSONArray();
for(User user : onlineUsers){
usersJsonArray.put(new JSONObject(user));
}
message.put("onlineUsers",usersJsonArray);
responseMessage.setMessage(message.toString());
responseMessage.setMessageType(ResponseMessage.Type.PAGE_ONLINE_USERLIST.toString());
responseMessage.setRemark("Is onLine user lists");
//responseMessage.setUser((User)request.getSession().getAttribute("user"));
responseMessage.setToUser(null);
return responseMessage;
}
@RequestMapping(value="/login")
public @ResponseBody String login(HttpServletRequest request, String userName, String password){
User user = new User();
user.setId(Long.valueOf(new Date().getTime()).intValue());
user.setUserName(userName);
user.setPwd(password);
HttpSession session = request.getSession();
session.setAttribute("user",user);
JSONObject response = new JSONObject(user);
return response.toString();
}
@MessageMapping(value="/chat")
@SendTo("/topic/getResponse")
public ResponseMessage chat(UserSendMessage userSendMessage,Principal principal){
User user=null;
List<User> onlineUsers = WebSocketConfig.onlineUsers;
for(User onLineUser : onlineUsers){
if(String.valueOf(userSendMessage.getUserId()).equals(String.valueOf(onLineUser.getId()))){
logger.info("找到用户....");
user = onLineUser;
}
}
//有人上线 , 构造上线提醒
ResponseMessage responseMessage = new ResponseMessage();
responseMessage.setMessage(userSendMessage.getMsg());
responseMessage.setRemark("user send msg in chatpanel");
responseMessage.setToUser(null);
responseMessage.setUser(user);
responseMessage.setMessageType(ResponseMessage.Type.PAGE_USER_SENDMESSAGE.toString());
return responseMessage;
}
FileOutputStream output;
public void handleBinaryMessage(WebSocketSession session, BinaryMessage message)
{
ByteBuffer buffer= message.getPayload();
try {
output.write(buffer.array());
} catch (IOException e) {
e.printStackTrace();
}
}
}
然后再页面上定义sockjs访问格式和路径拼装
<script th:src="@{js/jquery.min.js}"></script>
<script th:src="@{js/Helper.js}"></script>
<script th:src="@{js/keyboard.js}"></script>
<script th:src="@{js/const.js}"></script>
<script th:src="@{js/level.js}"></script>
<script th:src="@{js/crackAnimation.js}"></script>
<script th:src="@{js/prop.js}"></script>
<script th:src="@{js/bullet.js}"></script>
<script th:src="@{js/tank.js}"></script>
<script th:src="@{js/num.js}"></script>
<script th:src="@{js/menu.js}"></script>
<script th:src="@{js/map.js}"></script>
<script th:src="@{js/Collision.js}"></script>
<script th:src="@{js/stage.js}"></script>
<script th:src="@{js/main.js}"></script>
function connect(){
var userName = null;
while(userName==null || userName==''){
userName = prompt("请输入你的名字 , 我们将为你注册且登录:");
}
$.ajax({
url:'/login',
data: {
'userName':userName,
'password':'222'
},
type:'post',
dataType:'json',
success : function (data) {
userId = data.id;
if(data.userName !=undefined){
//stompClient = Stomp.over("/endpointWisely");
//连接点
var socket = new SockJS('/endpointWisely');
stompClient = Stomp.over(socket);
stompClient.connect({},function (frame) {
setConnected(true);
console.log("Connected : "+frame);
stompClient.subscribe('/topic/getResponse',function (response) {
var data = JSON.parse(response.body);
var msgType = data.messageType;
switch (msgType){
case "PAGE_ONLINE_USERLIST":
var message = data.message;
message =JSON.parse(message);
onLineListUpdate(message.onlineUsers);
break;
case "PAGE_USER_ONLINE_NOTIFY":
var message = data.message;
message =JSON.parse(message);//要把字符串转为JSON对象
var who = message.userName;
addMsgBox(who+" 现在上线了","standard");
//在线列表用户变化 , 重新更新
getOnlineUsers();
break;
case "PAGE_USER_OFFLINE_NOTIFY":
var message = data.message;
message =JSON.parse(message);
var who = message.userName;
addMsgBox(who+" 下线回家了","standard");
//在线列表用户变化 , 重新更新
getOnlineUsers();
break;
case "PAGE_USER_SENDMESSAGE":
var message = data.message;
var who = data.user.userName;
var userIdTemp = data.user.id;
//发布订阅都会接受所有消息,过滤自己的消息
if(userIdTemp!=userId){
addMsgBox(who+" 说 : "+message,"standard");//自己的话不显示
}
break;
default :
break;
}
});
});
}
}
});
}
file:///C:\Users\liyu\AppData\Local\Temp\ksohtml\wps2316.tmp.jpg
file:///C:\Users\liyu\AppData\Local\Temp\ksohtml\wps3343.tmp.jpg
file:///C:\Users\liyu\AppData\Local\Temp\ksohtml\wps4843.tmp.jpg
码云地址:https://gitee.com/liyusb/springbootWebscoketShiXianDaiMa.git |
|