WebSocket實現服務器與客戶端握手
自學的WebSocket途中遇到很多坑,希望需要使用的朋友可以少走彎路,
使用的環境:tomcat7.0,mysql,springMvc,spring,Mybatis
主要使用2個jar包 這2個jar包在tomcat7的 lib文件夾裏面有
catalina.jar websocket-api.jar
其他jar包截圖如下
本章實例中,實現了客戶端之間的通信和服務器響應數據給客戶端
1.客戶端之間的通信,打開2個瀏覽器模仿QQ聊天功能
2.服務器與客戶端之間的通信
當數據庫信息發生改變時候,服務器把最新的數據響應給客戶端
這是數據沒改變的時候的
當數據庫發生改變時候,服務器把最新的數據推送給客戶端
沒改變的時候,服務器不會推送數據
主要類3個
GetHttpSession用與在MyWebSocket類中獲取HttpSession對象
package ljm.web;
import javax.servlet.http.HttpSession;
import javax.websocket.HandshakeResponse;
import javax.websocket.server.HandshakeRequest;
import javax.websocket.server.ServerEndpointConfig;
public class GetHttpSession extends ServerEndpointConfig.Configurator
{
@Override
public void modifyHandshake(ServerEndpointConfig config,
HandshakeRequest request,HandshakeResponse response){
HttpSession httpSession = (HttpSession)request.getHttpSession();
config.getUserProperties().put(HttpSession.class.getName(),httpSession);
}
}
MyWebSocket用實現服務器與客戶端的通信
package ljm.web;
import java.io.IOException;
import java.util.concurrent.CopyOnWriteArraySet;
import javax.servlet.http.HttpSession;
import javax.websocket.EndpointConfig;
import javax.websocket.OnClose;
import javax.websocket.OnError;
import javax.websocket.OnMessage;
import javax.websocket.OnOpen;
import javax.websocket.Session;
import javax.websocket.server.ServerEndpoint;
import org.springframework.web.context.ContextLoader;
import ljm.service.UserService;
@ServerEndpoint(value="/chat",configurator=GetHttpSession.class)
public class MyWebSocket {
private UserService userService = (UserService) ContextLoader.getCurrentWebApplicationContext().getBean("userService");
//靜態變量,用來記錄當前在線連接數。應該把它設計成線程安全的。
private static int onlineCount = 0;
//更新數據的線程
RefreshThread thread =null;
//concurrent包的線程安全Set,用來存放每個客戶端對應的MyWebSocket對象。若要實現服務端與單一客戶端通信的話,可以使用Map來存放,其中Key可以爲用戶標識
private static CopyOnWriteArraySet<MyWebSocket> webSocketSet = new CopyOnWriteArraySet<MyWebSocket>();
//與某個客戶端的連接會話,需要通過它來給客戶端發送數據
private Session session;
/**
* 連接建立成功調用的方法
* @param session 可選的參數。session爲與某個客戶端的連接會話,需要通過它來給客戶端發送數據
* @throws Exception
*/
@OnOpen
public void onOpen(Session session,EndpointConfig config) throws Exception{
Integer age=userService.findUserAge(1);
System.out.println(age);
this.session = session;
webSocketSet.add(this);
HttpSession se= (HttpSession) config.getUserProperties().get(HttpSession.class.getName());
se.setAttribute("userId", 1);
thread=new RefreshThread(session,se);
thread.start();
addOnlineCount(); //在線數加1
System.out.println("有新連接加入!當前在線人數爲" + getOnlineCount());
}
/**
* 連接關閉調用的方法
*/
@OnClose
public void onClose(){
thread.stopThread();
webSocketSet.remove(this); //從set中刪除
subOnlineCount(); //在線數減1
System.out.println("有一連接關閉!當前在線人數爲" + getOnlineCount());
}
/**
* 收到客戶端消息後調用的方法
* @param message 客戶端發送過來的消息
* @param session 可選的參數
*/
@OnMessage
public void onMessage(String message, Session session) {
System.out.println("來自客戶端的消息:" + message);
//羣發消息
for(MyWebSocket item: webSocketSet){
try {
item.sendMessage(message);
} catch (IOException e) {
e.printStackTrace();
continue;
}
}
}
/**
* 發生錯誤時調用
* @param session
* @param error
*/
@OnError
public void onError(Session session, Throwable error){
System.out.println("發生錯誤");
error.printStackTrace();
}
/**
* 這個方法與上面幾個方法不一樣。沒有用註解,是根據自己需要添加的方法。
* @param message
* @throws IOException
*/
public void sendMessage(String message) throws IOException{
//同步
this.session.getBasicRemote().sendText(message);
//異步this.session.getAsyncRemote().sendText(message);
}
public static synchronized int getOnlineCount() {
return onlineCount;
}
public static synchronized void addOnlineCount() {
MyWebSocket.onlineCount++;
}
public static synchronized void subOnlineCount() {
MyWebSocket.onlineCount--;
}
}
RefreshThread線程用於查詢數據庫有沒有新的通知信息
package ljm.web;
import javax.servlet.http.HttpSession;
import javax.websocket.Session;
import org.springframework.web.context.ContextLoader;
import ljm.service.UserService;
public class RefreshThread extends Thread {
private Session session;
private Integer currentAge;
private HttpSession se;
UserService userService;
private volatile boolean stop = false;
//關閉線程
public void stopThread() {
this.stop = true;
}
public RefreshThread(Session session,HttpSession se) throws Exception {
userService = (UserService) ContextLoader.getCurrentWebApplicationContext().getBean("userService");
this.session = session;
this.se=se;
currentAge =userService.findUserAge((Integer) se.getAttribute("userId")) ;//此時是0條最新消息
}
@Override
public void run() {
Integer age=null;
while (true) {
try {
Integer id=(Integer) se.getAttribute("userId");
age=userService.findUserAge(id);
if(age!=currentAge){
session.getBasicRemote().sendText(age+"");
currentAge=age;
}
//一秒刷新一次
Thread.sleep(1000);
} catch (Exception e) {
e.printStackTrace();
}
}
}
}
其次就是配置要通訊的JSP頁面<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>
<%
String path = request.getContextPath();
String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";
%>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
<head>
<base href="<%=basePath%>">
<title>My JSP 'index.jsp' starting page</title>
<meta http-equiv="pragma" content="no-cache">
<meta http-equiv="cache-control" content="no-cache">
<meta http-equiv="expires" content="0">
<meta http-equiv="keywords" content="keyword1,keyword2,keyword3">
<meta http-equiv="description" content="This is my page">
</head>
<body>
Welcome<br/>
<input id="text" type="text" /><button onclick="send()">Send</button> <button onclick="closeWebSocket()">Close</button>
<div id="message">
</div>
</body>
<script type="text/javascript">
var websocket = null;
//判斷當前瀏覽器是否支持WebSocket
if('WebSocket' in window){
websocket = new WebSocket("ws://localhost:8080/webSocketDemo/chat");
}
else{
alert('Not support websocket');
}
//連接發生錯誤的回調方法
websocket.onerror = function(){
setMessageInnerHTML("error");
};
//連接成功建立的回調方法
websocket.onopen = function(event){
setMessageInnerHTML("open");
};
//接收到消息的回調方法
websocket.onmessage = function(event){
setMessageInnerHTML(event.data);
};
//連接關閉的回調方法
websocket.onclose = function(){
setMessageInnerHTML("close");
};
//監聽窗口關閉事件,當窗口關閉時,主動去關閉websocket連接,防止連接還沒斷開就關閉窗口,server端會拋異常。
window.onbeforeunload = function(){
websocket.close();
};
//將消息顯示在網頁上
function setMessageInnerHTML(innerHTML){
document.getElementById('message').innerHTML += innerHTML + '<br/>';
}
//關閉連接
function closeWebSocket(){
websocket.close();
}
//發送消息
function send(){
var message = document.getElementById('text').value;
websocket.send(message);
}
</script>
</html>
注意事項
如果有問題不懂得朋友和需要實例的朋友發郵件到: [email protected]