packagewebsockets;importjava.io.IOException;importjava.io.PrintWriter;importjava.text.SimpleDateFormat;importjava.util.Date;importjava.util.Map;importjavax.servlet.ServletException;importjavax.servlet.annotation.WebServlet;importjavax.servlet.http.HttpServlet;importjavax.servlet.http.HttpServletRequest;importjavax.servlet.http.HttpServletResponse;importorg.apache.commons.lang.time.DateFormatUtils;importorg.json.JSONArray;importorg.json.JSONException;importorg.json.JSONObject;importorg.springframework.http.server.ServletServerHttpRequest;importHelper.AAAAYulebaoShareSingleton;importHelper.MySqlHepler2;importHelper.EncryptSafa;importjava.io.IOException;importjava.util.concurrent.CopyOnWriteArraySet;import javax.websocket.*;importjavax.websocket.server.PathParam;importjavax.websocket.server.ServerEndpoint;//auth:liaohang
@ServerEndpoint("/javaWebSocket")public classjavaWebSocket {//静态变量,用来记录当前在线连接数。应该把它设计成线程安全的。
private static int onlineCount = 0;//concurrent包的线程安全Set,用来存放每个客户端对应的MyWebSocket对象。若要实现服务端与单一客户端通信的话,可以使用Map来存放,其中Key可以为用户标识//private static CopyOnWriteArraySet webSocketSets = new CopyOnWriteArraySet();
private static JSONObject webSocketSets = newJSONObject();//与某个客户端的连接会话,需要通过它来给客户端发送数据
privateSession session;privateString[] parameterArr;privateString shareStr;privateString userKey;privateString shopKey;privateString type;//这里来个请求的httpRequest类
/*** 连接建立成功调用的方法
*@paramsession 可选的参数。session为与某个客户端的连接会话,需要通过它来给客户端发送数据*/
privatejavaWebSocket chatmemeber;//数据库操作参数
private MySqlHepler2 helper=newMySqlHepler2();privateJSONArray returnJsonArray;private String[] mysqlParameter=null;privateJSONObject shareObject;privateString datatime;private int shareInt=0;
@OnOpenpublic voidonOpen(Session session){this.session =session;
shareStr=session.getRequestURI().toString();
shareStr=shareStr.replace("/yulebaoServlet/javaWebSocket?", "");
shareStr=shareStr.replace("user=", "");
shareStr=shareStr.replace("shop=", "");
shareStr=shareStr.replace("type=", "");
parameterArr=shareStr.split("&");
type=parameterArr[2];if(type.equals("user"))
{
userKey=parameterArr[0];
shopKey=parameterArr[1];
webSocketSets.put(userKey,this);//查询一次数据库,看是有人在我离线时给我发了消息
mysqlParameter=newString[]{userKey};
returnJsonArray=helper.executeQueryT("select * from AAAAAAAAAChatSheet where sessionKey=?", mysqlParameter);try{
shareInt=returnJsonArray.length();
}catch(Exception e) {
shareInt=0;
}if(returnJsonArray.length()>0)
{
shareObject=returnJsonArray.getJSONObject(0);
shareStr= shareObject.getString("chatContentArray");try{this.sendMessage(shareStr);
}catch(IOException e) {
e.printStackTrace();
}
mysqlParameter=newString[]{userKey};
helper.executeUpdate("delete from AAAAAAAAAChatSheet where sessionKey=?", mysqlParameter);
}
}else{
userKey=parameterArr[0];
shopKey=parameterArr[1];
webSocketSets.put(shopKey,this);//查询一次数据库,看是有人在我离线时给我发了消息
mysqlParameter=newString[]{shopKey};
returnJsonArray=helper.executeQueryT("select * from AAAAAAAAAChatSheet where sessionKey=?", mysqlParameter);try{
shareInt=returnJsonArray.length();
}catch(Exception e) {
shareInt=0;
}if(returnJsonArray.length()>0)
{
shareObject=returnJsonArray.getJSONObject(0);
shareStr= shareObject.getString("chatContentArray");try{this.sendMessage(shareStr);
}catch(IOException e) {
e.printStackTrace();
}//删除key
mysqlParameter=newString[]{shopKey};
helper.executeUpdate("delete from AAAAAAAAAChatSheet where sessionKey=?", mysqlParameter);
}
}//加入set中
addOnlineCount(); //在线数加1
System.out.println("有新连接加入!当前在线人数为" +getOnlineCount());
}/*** 连接关闭调用的方法*/@OnClosepublic voidonClose(){if(type.equals("user"))
{if(!webSocketSets.isNull(userKey))
{
webSocketSets.remove(userKey);
}
}else{if(!webSocketSets.isNull(shopKey))
{
webSocketSets.remove(shopKey);
}
}//从set中删除
subOnlineCount(); //在线数减1
System.out.println("有一连接关闭!当前在线人数为" +getOnlineCount());
}/*** 收到客户端消息后调用的方法
*@parammessage 客户端发送过来的消息
*@paramsession 可选的参数*/@OnMessagepublic voidonMessage(String message, Session session) {
System.out.println("来自客户端的消息:" +message);//群发消息
if(type.equals("user"))
{if(!webSocketSets.isNull(shopKey))
{
chatmemeber=(javaWebSocket)webSocketSets.get(shopKey);try{
chatmemeber.sendMessage(message);
}catch(IOException e) {
e.printStackTrace();
}
}else{
insertDataBase(shopKey,message);
}
}else{if(!webSocketSets.isNull(userKey))
{
chatmemeber=(javaWebSocket)webSocketSets.get(userKey);try{
chatmemeber.sendMessage(message);
}catch(IOException e) {
e.printStackTrace();
}
}else{//接消息以方不在,插入数据库保存
insertDataBase(userKey,message);
}
}//1对多发消息
/*for(javaWebSocket item: webSocketSets){
try {
item.sendMessage(message);
} catch (IOException e) {
e.printStackTrace();
continue;
}
}*/}/*** 发生错误时调用
*@paramsession
*@paramerror*/@OnErrorpublic voidonError(Session session, Throwable error){
System.out.println("发生错误");
error.printStackTrace();
}/*** 这个方法与上面几个方法不一样。没有用注解,是根据自己需要添加的方法。
*@parammessage
*@throwsIOException*/
public void sendMessage(String message) throwsIOException{this.session.getBasicRemote().sendText(message);//this.session.getAsyncRemote().sendText(message);
}public static synchronized intgetOnlineCount() {returnonlineCount;
}public static synchronized voidaddOnlineCount() {
javaWebSocket.onlineCount++;
}public static synchronized voidsubOnlineCount() {
javaWebSocket.onlineCount--;
}//当一方用户下线之后,如果再发消息,需要将接收消息保存到数据库
public voidinsertDataBase(String shareKey,String message)
{
shareObject=newJSONObject();
datatime=DateFormatUtils.format(new Date(), "yyyy-MM-dd HH:mm");
shareObject.put("datatime", datatime);
shareObject.put("message", message);
mysqlParameter=newString[]{shareKey};
returnJsonArray=helper.executeQueryT("select * from AAAAAAAAAChatSheet where sessionKey=?", mysqlParameter);try{
shareInt=returnJsonArray.length();
}catch(Exception e)
{
shareInt=0;
returnJsonArray=newJSONArray();
}if(shareInt==0) //插入数据
{
returnJsonArray.put(shareObject);
mysqlParameter=newString[]{shareKey,datatime,returnJsonArray.toString()};
helper.executeUpdate("insert into AAAAAAAAAChatSheet(sessionKey,sessionCreateTimes,chatContentArray)values(?,?,?)", mysqlParameter);
}else//更新连端的数据
{
returnJsonArray.put(shareObject);
mysqlParameter=newString[]{returnJsonArray.toString(),shareKey};
helper.executeUpdate("update AAAAAAAAAChatSheet set chatContentArray=? where sessionKey=?", mysqlParameter);
}
}
}