標籤:java websocket
Java WebSocket
依賴環境tomcat8.0及以上
兩種配置方式
1.註解式配置
//範例程式碼
@ServerEndpoint("/chat")
public class Chat{
//建立串連時調用,可傳入的參數Session(WebSocket的Session,在SpringWebSocket裡面則是WebSocketSession),EndpointConfig,和帶@PathParam注的參數
@OnOpen
public void onOpen(Session session,EndpoingConfig config){
}
//訊息到來時調用,可傳入的參數Session(WebSocket的Session,在SpringWebSocket裡面則是WebSocketSession),根據訊息的形式,如果是簡訊,傳入String型別參數或者Reader,如果是二進位訊息,傳入byte[]型別參數或者InputStream,如果Pong訊息傳入實現了PongMessage介面的型別參數,方法還可以帶傳回型別,如果有傳回型別,比如String(還可以是byte[]或ByteBuffer),則是立即向用戶端發送String訊息,如果是分區訊息(訊息有whole,partial兩種,全部訊息和分區訊息),還可傳入boolean類型的參數,判斷是否到了分區的結尾。
@OnMessage//處理簡訊
public void onMessage(Session session,String message,boolean isLast){
}
@OnMessage//處理二進位訊息,參數隨便搭配
public void onMessage(Session session,byte[] message,boolean isLast){
}
//傳輸發生錯誤時調用,可傳入參數Session,Throwable
@OnError
public void onError(Session session,Throwable t){
}
@OnClose//串連關閉時調用,可能一方主動關閉,或者連線逾時的關閉
public void onClose(CloseReason cr){
}
}
2.編程式配置//繼承Endpoint
public class Program extends Endpoint{
@Override
public void onOpen(Session session, EndpointConfig endpointConfig) {
session.addMessageHandler(new MessageHandler.Whole<String>() {
@Override
public void onMessage(String text) {
try {
//可以擷取同步的遠程端點和同步的,以此發送同步訊息或非同步訊息
mySession.getBasicRemote().sendText("I got this (" +text + ") so I am sending it back !");
} catch (IOException ioe) {
System.out.println("oh dear, something went wrong trying to send the message back: " + ioe.getMessage());
}
}
});
}
//還有onError()和onClose()方法,不寫了
}
//配置映射uri,實現ServerApplicationConfig
public class ProgramAppConfig implements ServerApplicationConfi{
//參數是WebSocket會傳入掃描到的所有帶有@ServerEndpoint註解的類集合,WebSocket會調用這個方法擷取這些集合,如果沒什麼要做的,直接把參數返回就行了
public Set<Class<?>> getAnnotatedEndpointClasses(Set<Class<?>> scanned){
return scanned;
}
//WebSocket會傳入繼承了Endpoint類的集合,但是返回的是ServerEndpointConfig集合,需要做一個轉換
public Set<ServerEndpointConfig> getEndpointConfigs(Set<Class<? extends Endpoint>> endpointClasses){
Set<ServerEndpointConfiguration> configs = new HashSet<ServerEndpointConfiguration>();
ServerEndpointConfiguration sec = ServerEndpointConfigurationBuilder.create(Program .class, "/program").build();
configs.add(sec);
return configs;
}
}
安全執行緒問題
每次請求Webocket都會執行個體化一個新的端點,就像HttpSession一樣,請求之間互補幹擾,不需要我們處理多線程問題
Tomcat8.0 支援的WebSocket 總結