【实例简介】
【实例截图】
【核心代码】
package com.example.demo;
import java.io.IOException;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.concurrent.ConcurrentHashMap;
import javax.websocket.OnClose;
import javax.websocket.OnMessage;
import javax.websocket.OnOpen;
import javax.websocket.Session;
import javax.websocket.server.PathParam;
import javax.websocket.server.ServerEndpoint;
import org.springframework.stereotype.Component;
import net.sf.json.JSONObject;
@ServerEndpoint(value = "/websocket/{userno}")
@Component
public class MyWebSocket {
//静态变量,用来记录当前在线连接数。应该把它设计成线程安全的。
private static int onlineCount = 0;
private static SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
//concurrent包的线程安全Set,用来存放每个客户端对应的MyWebSocket对象。
// private static CopyOnWriteArraySet webSocketSet = new CopyOnWriteArraySet();
//concurrent包的线程安全Set,用来存放每个客户端对应的MyWebSocket对象。若要实现服务端与单一客户端通信的话,可以使用Map来存放,其中Key可以为用户标识
private static ConcurrentHashMap webSocketSet = new ConcurrentHashMap();
//与某个客户端的连接会话,需要通过它来给客户端发送数据
private Session session;
//当前发消息的人员编号
private String userno = "";
/**
* 连接建立成功调用的方法*/
@OnOpen
public void onOpen(@PathParam(value = "userno") String param,Session session) {
System.out.println(param);
userno = param;//接收到发送消息的人员编号
this.session = session;
addOnlineCount();
webSocketSet.put(param, this);//加入map中
System.out.println("有新连接加入!当前在线人数为" getOnlineCount());
String nickname="{'nickname':'" param "','content':'上线'}";
JSONObject obj = JSONObject.fromObject(nickname);
try {
sendMessage(obj "");
} catch (IOException e) {
System.out.println("IO异常");
}
}
/**
* 连接关闭调用的方法
*/
@OnClose
public void onClose() {
webSocketSet.remove(this); //从set中删除
subOnlineCount(); //在线数减1
System.out.println("有一连接关闭!当前在线人数为" getOnlineCount());
}
/**
* 收到客户端消息后调用的方法
*
* @param message 客户端发送过来的消息*/
@OnMessage
public void onMessage(String message, Session session) {
System.out.println("来自客户端的消息:" message);
System.out.println("来自客户端的消息:" message);
// session.get
sendToUser(message);
//群发消息
/* if (1 < 2) {
sendAll(message);
} else {
//给指定的人发消息
sendToUser(message);
}*/
}
/**
* 给指定的人发送消息
* @param message
*/
private void sendToUser(String message) {
// String sendUserno = message.split("[|]")[1];
// String sendMessage = message.split("[|]")[0];
JSONObject obj = JSONObject.fromObject(message);
obj.put("date", df.format(new Date()));
String now = getNowTime();
try {
Object object2 = obj.get("nickname2");
if (webSocketSet.get(obj.get("nickname")) != null) {
obj.put("isSelf", false);
Object object = obj.get("content");
webSocketSet.get(obj.get("nickname")).sendMessage(obj.toString());
}
if(webSocketSet.get(object2) != null){
obj.put("isSelf", true);
Object object = obj.get("content");
webSocketSet.get(obj.get("nickname2")).sendMessage(obj.toString());
}
} catch (IOException e) {
e.printStackTrace();
}
}
/**
* 给所有人发消息
* @param message
*/
private void sendAll(String message) {
String now = getNowTime();
String sendMessage = message.split("[|]")[0];
//遍历HashMap
for (String key : webSocketSet.keySet()) {
try {
//判断接收用户是否是当前发消息的用户
if (userno.equals(key)) {
webSocketSet.get(key).sendMessage(now "用户" userno "发来消息:" "
" sendMessage);
System.out.println("key = " key);
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
/**
* 获取当前时间
*
* @return
*/
private String getNowTime() {
Date date = new Date();
DateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
String time = format.format(date);
return time;
}
public void sendMessage(String message) throws IOException{
this.session.getBasicRemote().sendText(message);
//this.session.getAsyncRemote().sendText(message);
}
/**
* 发生错误时调用
@OnError
public void onError(Session session, Throwable error) {
System.out.println("发生错误");
error.printStackTrace();
}
public void sendMessage(String message) throws IOException {
this.session.getBasicRemote().sendText(message);
//this.session.getAsyncRemote().sendText(message);
}
/**
* 群发自定义消息
* */
public static void sendInfo(String message) throws IOException {
}
public static synchronized int getOnlineCount() {
return onlineCount;
}
public static synchronized void addOnlineCount() {
MyWebSocket.onlineCount ;
}
public static synchronized void subOnlineCount() {
MyWebSocket.onlineCount--;
}
}