sprintboot的websocket demo,网上都是写的啥玩意,整理一下,来个简洁版本的,而且相当稳定的说,记录一下
WebSocketServer类:
import org.springframework.stereotype.Component;
import javax.websocket.*;
import javax.websocket.server.PathParam;
import javax.websocket.server.ServerEndpoint;
import java.io.IOException;
import java.util.Map;
@ServerEndpoint("/webSocket/access")
@Component
public class WebSocketServer {
//建立连接成功调用
@OnOpen
public void onOpen(Session session){
//session.getRequestParameterMap()也可以获取到所有参数,但是我就是不喜欢用,你说可气不
//Map<java.lang.String,java.util.List<java.lang.String>> ps = session.getRequestParameterMap();
//解析连接中所有的参数,并将参数放入到UserProperties中,以便后面onMessage时,方便的获取参数
Map queryMap = RequestUtil.getQueryParamsMap(session.getQueryString());
if(queryMap!=null){
session.getUserProperties().putAll(queryMap);
}
System.out.println("新用户加入webSocket!当前人数为" + (session.getOpenSessions().size()+1));
try {
sendMessage(session, "欢迎加入连接!");
} catch (IOException e) {
e.printStackTrace();
}
}
//关闭连接时调用
@OnClose
public void onClose(Session session){
System.out.println(session.getUserProperties().get("userName") + "断开webSocket连接!当前人数为" + session.getOpenSessions().size());
}
//收到客户端信息
@OnMessage
public void onMessage(Session session,String message) throws IOException{
String userName = (String)session.getUserProperties().get("userName");
message = "["+userName+"]说:" + message;
System.out.println(message);
sendToAll(session,message);
}
//错误时调用
@OnError
public void onError(Session session, Throwable throwable){
System.out.println("发生错误");
throwable.printStackTrace();
}
private void sendToAll(Session session,String message) {
for (Session t_session: session.getOpenSessions()) {
try {
if(t_session==session){
continue;
}
sendMessage(t_session, message);
} catch(Exception e){
e.printStackTrace();
continue;
}
}
}
//发送消息
public void sendMessage(Session session, String message) throws IOException {
if(session != null){
synchronized (session) {
// System.out.println("发送数据:" + message);
session.getAsyncRemote().sendText(message);
}
}
}
}
RequestUtil类:
import javax.servlet.http.HttpServletRequest;
import java.io.UnsupportedEncodingException;
import java.net.URLDecoder;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
public class RequestUtil {
/**
* 将request所有参数都存放到map中
*
* @param queryStr
* @return
*/
public static Map<String, String> getQueryParamsMap(String queryStr) {
Map<String, String> params = new HashMap<String, String>();
if(queryStr!=null && queryStr.trim().length()>0 && queryStr.contains("=")){
try {
queryStr = URLDecoder.decode(queryStr,"utf-8");
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
String[] kvs = queryStr.split("&");
if(kvs!=null && kvs.length>0){
for(String kv:kvs){
String[] kvp = kv.split("=");
if(kvp!=null && kvp.length==2){
params.put(kvp[0],kvp[1]);
}
}
}
}
return params;
}
}