package org.springblade.subway.sokcet;//package org.springblade.subway.socket;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import org.java_websocket.WebSocket;
import org.java_websocket.WebSocketImpl;
import org.java_websocket.handshake.ClientHandshake;
import org.java_websocket.server.WebSocketServer;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.net.InetSocketAddress;
import java.net.UnknownHostException;
import java.util.Map;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;/**
* WebSocket 即时通信 在线管理
* @author yxl
**/
public classOnlineChatServer extends WebSocketServer{private static Logger logger = LoggerFactory.getLogger(OnlineChatServer.class);static ExecutorService fixedThreadPool = Executors.newFixedThreadPool(32);public OnlineChatServer(intport) throws UnknownHostException {
super(newInetSocketAddress(port));
}publicOnlineChatServer(InetSocketAddress address) {
super(address);
}/**
* 客户端发送消息到服务器时触发事件*/@Overridepublic voidonMessage(WebSocket conn, String message){
logger.info("message:" +message);
JSONObject parseObject=JSON.parseObject(message);
Object function= parseObject.get("business");
System.out.println("body:"+parseObject.get("body"));try{if(parseObject.get("business").equals("login")){this.userjoin(parseObject.get("user").toString(),conn);
}
}catch(Exception e) {
e.printStackTrace();
}
}//--------------------------------------------公共方法------------------------------------------------
/**
* 触发异常事件*/@Overridepublic voidonError( WebSocket conn, Exception ex ) {
System.out.println("连接失败");
ex.printStackTrace();if( conn != null) {//some errors like port binding failed may not be assignable to a specific websocket
}
}/**
* 触发连接事件*/@Overridepublic voidonOpen( WebSocket conn, ClientHandshake handshake ) {
System.out.println("用户连接WebSocket成功===" +conn.getRemoteSocketAddress().getAddress().getHostAddress());
}/**
* 触发关闭事件*/@Overridepublic void onClose( WebSocket conn, intcode, String reason, boolean remote ) {
userLeave(conn);
}///**//* 用户加入处理//* @param user//*/
public voiduserjoin(String user, WebSocket conn){
logger.info("========================================================================");
logger.info("userjoin:" +user);
logger.info("========================================================================");
onlineMaganger(1,user,conn);
}/**
* 用户下线处理*/
public voiduserLeave(WebSocket conn){
onlineMaganger(2,null,conn);
}///**//* 获取在线总数//* @param user//*///public void getUserCount(WebSocket conn){//JSONObject result = new JSONObject();//result.put("type", "count");//result.put("msg", OnlineChatServerPool.getUserCount());//OnlineChatServerPool.sendMessageToUser(conn,result.toString());//}
/**
* 获取在线总数
* @param search*/
public void getGpsList(WebSocket conn, Mapsearch){
JSONObject result= newJSONObject();
result.put("type", "count");
result.put("msg", OnlineChatServerPool.getUserCount());
OnlineChatServerPool.sendMessageToUser(conn,result.toString());
}//
///**//* 获取在线用户列表//* @param user//*///public void getUserList(){//WebSocket conn = OnlineChatServerPool.getWebSocket();//if(ObjectHelper.isEmpty(conn)){return;}//JSONObject result = new JSONObject();//result.put("type", "userlist");//result.put("list", OnlineChatServerPool.getOnlineUser());//OnlineChatServerPool.sendMessageToUser(conn,result.toString());//}
/**用户上下线管理
* @param type 1:上线;2:下线
* @param user
* @param conn*/
public synchronized void onlineMaganger(inttype,String user, WebSocket conn){if(type == 1){//判断用户是否在其它终端
WebSocket uSocket =OnlineChatServerPool.getWebSocketByUser(user);if (null ==uSocket) {//向连接池添加当前的连接对象
OnlineChatServerPool.addUser(user,conn);
OnlineChatServerPool.setWebSocket(conn);
}
}else{
OnlineChatServerPool.removeUser(conn);//在连接池中移除连接
}
}/**
* 启动在线管理服务*/
public static voidstartWebsocketOnline(){
WebSocketImpl.DEBUG= false;
OnlineChatServer s;try{
s= new OnlineChatServer(8022);
s.start();
System.out.println("socket started");
}catch(UnknownHostException e) {
e.printStackTrace();
}
}public static voidmain(String[] args){
startWebsocketOnline();//OnlineChatServerPool.sendMessage("hello socket");
}
}