WebSocket 使得客户端和服务器之间的数据交换变得更加简单,允许服务端主动向客户端推送数据。在 WebSocket API 中,浏览器和服务器只需要完成一次握手,两者之间就直接可以创建持久性的连接,并进行双向数据传输。
下面是一个简单的案例:
js:
var Chat = {};
Chat.socket = null;
Chat.connect = (function() {
if ('WebSocket' in window) {
//WebSocket请求连接
Chat.socket = new WebSocket("ws://localhost:8080/ws");
} else if ('MozWebSocket' in window) {
Chat.socket = new MozWebSocket("");
} else {
alert('该浏览器暂不支持WebSocket');
return;
}
Chat.socket.onopen = function () {
console.log('消息推送webSocket连接服务器成功.');
};
Chat.socket.onclose = function () {
//console.log('关闭服务器连接.....');
};
//接收到消息
Chat.socket.onmessage = function (message) {
//查看什么类型的socket数据
var mes = eval('(' + message.data + ')');
var mesType = mes.type;
switch (mesType)
{
case '**':
//成功后操作
break;
}
}
});
Chat.initialize = function(user) {
if (window.location.protocol == 'http:') {
Chat.connect();
} else {
Chat.connect();
}
};
Chat.sendMessage = function(msg) {
Chat.socket.send(JSON.stringify(''));
};
Chat.initialize();
function sumMainx (m,n){
var num = Math.floor(Math.random()*(m - n) + n);
return num;
}
java:
import java.io.IOException;
import java.util.concurrent.CopyOnWriteArraySet;
import javax.websocket.OnClose;
import javax.websocket.OnError;
import javax.websocket.OnMessage;
import javax.websocket.OnOpen;
import javax.websocket.Session;
import javax.websocket.server.PathParam;
import javax.websocket.server.ServerEndpoint;
import org.slf4j.Logger;
import org.springframework.context.ApplicationContext;
import org.springframework.stereotype.Component;
import com.alibaba.druid.util.StringUtils;
@ServerEndpoint("/websocket/message/{userId}")
@Component
public class WebSocket {
//日志记录
private static final Logger log = org.slf4j.LoggerFactory.getLogger(WebSocket.class);
//静态变量,用来记录当前在线连接数。应该把它设计成线程安全的。
private static int onlineCount = 0;
//concurrent包的线程安全Set,用来存放每个客户端对应的MyWebSocket对象。
private static CopyOnWriteArraySet<WebSocket> webSocketSet = new CopyOnWriteArraySet<WebSocket>();
private static ApplicationContext applicationContext;
//与某个客户端的连接会话,需要通过它来给客户端发送数据
private Session session;
//接收者的用户Id
private String userId="";
/**
* 连接建立成功调用的方法*/
@OnOpen
public void onOpen(Session session,@PathParam("userId") String userId) {
this.session = session;
webSocketSet.add(this); //加入set中
addOnlineCount(); //在线数加1
log.info("消息提醒:webSocket连接连接成功, userId: "+userId+" 当前在线人数为" + getOnlineCount());
this.userId=userId;
}
/**
* 连接关闭调用的方法
*/
@OnClose
public void onClose() {
webSocketSet.remove(this); //从set中删除
subOnlineCount(); //在线数减1
log.info("消息提醒:userId: "+userId+" 连接关闭!当前在线人数为" + getOnlineCount());
}
/**
* 收到客户端消息后调用的方法
*
* @param message 客户端发送过来的消息*/
@OnMessage
public void onMessage(String message, Session session) {
log.info("消息提醒:收到来自userId: "+userId+" 的信息:"+message);
}
/**
*
* @param session
* @param error
*/
@OnError
public void onError(Session session, Throwable error) {
log.error("消息提醒:webSocket发生错误,连接关闭.");
error.printStackTrace();
}
/**
* 实现服务器主动推送
*/
public void sendMessage(String message) throws IOException {
this.session.getBasicRemote().sendText(message);
}
/**
* 群发自定义消息
* userId以","分隔
* */
public static boolean sendInfo(String message,@PathParam("userId") String userId) throws IOException {
if(StringUtils.isEmpty(userId)){
return false;
}
String [] userIds = userId.split(",");
if(userIds.length == 0){
return false;
}
for (WebSocket item : webSocketSet) {
for(String uid:userIds){
if(item.userId.equals(uid)){
try {
item.sendMessage(message);
} catch (Exception e) {
log.error("webSocket sendMessage Error: "+uid+" 消息发送失败!");
}
}
}
}
return true;
}
/**
* 主动关闭webSocket连接
* */
public static boolean closeBypdaid(@PathParam("userId") String userId) throws IOException {
if(StringUtils.isEmpty(userId)){
return false;
}
String [] userIds = userId.split(",");
if(userIds.length == 0){
return false;
}
for (WebSocket item : webSocketSet) {
for(String uid:userIds){
if(item.userId.equals(uid)){
try {
item.session.close();
} catch (Exception e) {
log.error("消息提醒:webSocket 关闭连接失败:"+uid);
}
}
}
}
return true;
}
public static synchronized int getOnlineCount() {
return onlineCount;
}
public static synchronized void addOnlineCount() {
WebSocket.onlineCount++;
}
public static synchronized void subOnlineCount() {
WebSocket.onlineCount--;
}
public static ApplicationContext getApplicationContext() {
return applicationContext;
}
public static void setApplicationContext(ApplicationContext applicationContext) {
WebSocket.applicationContext = applicationContext;
}
}