SlideShare a Scribd company logo
1 of 25
文孝義
國立中央大學資訊管理所 Ph.D
2014/3/121
Java API for WebSocket
大綱
2014/3/122
 簡介
 類型
 JAVA 平台
 Server Side: Java Servlet
 Client Slide: JavaScript for WebScoket
簡介
2014/3/123
 WebSocket 是種通訊協定,透過TCP 通訊協定提
供全工雙向通訊資料交換。
 針對WWW透過HTTP建立資料交換的需求。
 JSR-356
 Java API for WebSocket
 實作 RFC6455: The WebSocket Protocol
 Apache Tomcat 8 支援
 主流的瀏覽器都支援WebSocket且提供JavaScript
API
簡介
2014/3/124
 為何要採用 WebScoket?
 現有 HTTP 屬於短連接,用完即關閉。屬於無狀態
保存的通訊協定。
 實務上需要能夠即時傳遞資料。
 過去即時性資料交換,大多採用輪詢的方式。定時向
對方建立連線詢問。效能差,無法即時。
 適用:
 股市行情即時
 通訊軟體,Line等。
 訊息即時傳遞需要。
類型
2014/3/125
 WebSocket Application
 Server: 發佈 WebSoocket Endpoint 提供連線端
URIs
 Client: 使用 endpoint URIs來向 server 建立連線請求。
 WebSocket 通訊協定在完成建立連線後既已完成雙
方對稱狀態。任一方皆可發送與接受訊息。並且可以
隨意關閉連線。
Client
ServerClient
Client
類型
2014/3/126
 WebSocket 通訊協定
 Handshake: client 送出 WebSocket Endpoint URIs
進行交握機制來建立連線請求。交握機制是基於
HTTP為基礎架構上完成。
 Data trandfer
GET /path/to/websocket/endpoint HTTP/1.1
Host: localhost
Upgrade: websocket
Connection: Upgrade
Sec-WebSocket-Key: xqBt3ImNzJbYqRINxEFlkg==
Origin: http://localhost
Sec-WebSocket-Version: 13
HTTP/1.1 101 Switching Protocols
Upgrade: websocket
Connection: Upgrade
Sec-WebSocket-Accept:
K7DJLdLooIwIG/MOpvWFB3y3FE8
=
類型
2014/3/127
 支援的資料內容
 文字訊息 (以UTF-8編碼)
 二進制訊息,圖片、聲音或物件等。
 控制框格式
 Close
 Ping
 Pong
 Ping 的回應
 Ping 與 Pong 都是含有資料
類型
2014/3/128
 何謂 WebSocket Endpoint URIs?
 ws://host:port/path?query
 wss://host:port/path?query
 Port 部分是可省略,預設則是80或443。
 加密模式 HTTPS對應就是 wss
JAVA 平台
2014/3/129
 Java API for WebSocket (JSR-356)
 提供規範規格建立與佈署WebSocket endpoints的
Web 應用程式
 WebSocket client API 規範規格提供開發應用程式向
遠端WebSocket endpoints 存取操作
 javax.websocket.server 套件
 提供相關類別與介面建立與設定 server 端 endpoints
 javax.websocket 套件
 提供 client 與 server endpoints 共通介面與類別
JAVA 平台
2014/3/1210
 WebSocket endpoints 是
javax.websocket.Endpoint 的類別的物件實體。
 JSR-356 提供兩種endpoints方式來使用API
 Programmatic endpoints
 繼承 Endpoint類別使用相關方法
 Annotated endpoint
 使用 annotations 來操作方法
Server Side: Java Servlet
2014/3/1211
 Programmatic endpoints
public class EchoEndpoint extends Endpoint {
@Override
public void onOpen(final Session session, EndpointConfig config) {
session.addMessageHandler(new MessageHandler.Whole<String>()
@Override
public void onMessage(String msg) {
try {
session.getBasicRemote().sendText(msg);
} catch (IOException e) { ... }
}
});
}
}
Server Side: Java Servlet
2014/3/1212
 session 參數物件
 代表連線的雙方連線狀態
 佈署方式
 佈署後,其endpoint 如下
ServerEndpointConfig.Builder.create(EchoEndpoint.class, "/echo").build();
ws://localhost:8080/echoapp/echo
Server Side: Java Servlet
2014/3/1213
 Annotated endpoint
@ServerEndpoint("/echo")
public class EchoEndpoint {
@OnMessage
public void onMessage(Session session, String msg) {
try {
session.getBasicRemote().sendText(msg);
} catch (IOException e) { ... }
}
}
Server Side: Java Servlet
2014/3/1214
 相關方法
Annotatio
n
Event 說明
OnOpen 連線已經建立與
開啟
@OnOpen
public void open(Session session,
EndpointConfig conf) { }
OnMessa
ge
收到訊息 @OnMessage
public void message (Session
session,
String msg) { }
OnError 連線錯誤 @OnError
public void error(Session session,
Throwable error) { }
OnClose 連線已關閉 @OnClose
public void close(Session session,
CloseReason reason) { }
Client Slide: JavaScript for
WebScoket
2014/3/1215
 送收訊息
 使用 Session 取得 RemoteEndpoint物件
 Session.getBasicRemote()
 取得 RemoteEndpoint.Basic 物件的 blocking 方法
 Session.getAsyncRemote()
 取得 RemoteEndpoint.Async 物件的non-blocking方法
Client Slide: JavaScript for
WebScoket
2014/3/1216
 送出訊息
 文字訊息
 void RemoteEndpoint.Basic.sendText(String text)
 二進制訊息
 void RemoteEndpoint.Basic.sendBinary(ByteBuffer data)
 Ping 訊息
 void RemoteEndpoint.sendPing(ByteBuffer appData)
 Pong訊息
 void RemoteEndpoint.sendPong(ByteBuffer
appData)
Client Slide: JavaScript for
WebScoket
2014/3/1217
 取得全部已經連線所有session
 session.getOpenSessions()
@ServerEndpoint("/echoall")
public class EchoAllEndpoint {
@OnMessage
public void onMessage(Session session, String msg) {
try {
for (Session sess : session.getOpenSessions()) {
if (sess.isOpen())
sess.getBasicRemote().sendText(msg);
}
} catch (IOException e) { ... }
}
}
Client Slide: JavaScript for
WebScoket
2014/3/1218
 接收訊息類型
@ServerEndpoint("/receive")
public class ReceiveEndpoint {
@OnMessage
public void textMessage(Session session, String msg) {
System.out.println("Text message: " + msg);
}
@OnMessage
public void binaryMessage(Session session, ByteBuffer msg) {
System.out.println("Binary message: " + msg.toString());
}
@OnMessage
public void pongMessage(Session session, PongMessage msg) {
System.out.println("Pong message: " +
msg.getApplicationData().toString());
}
}
Client Slide: JavaScript for
WebScoket
2014/3/1219
 處理 client 端狀態
@ServerEndpoint("/delayedecho")
public class DelayedEchoEndpoint {
@OnOpen
public void open(Session session) {
session.getUserProperties().put("previousMsg", " ");
}
@OnMessage
public void message(Session session, String msg) {
String prev = (String)
session.getUserProperties().get("previousMsg");
session.getUserProperties().put("previousMsg", msg);
try {
session.getBasicRemote().sendText(prev);
} catch (IOException e) { ... }
}
}
Client Slide: JavaScript for
WebScoket
2014/3/1220
 其他
 Encoders與 Decoders
 處理資料型別的轉換
 Java Object to JSON/XML
 Path 參數
 把 URI 以參數方式處理
@ServerEndpoint("/chatrooms/{room-name}")
public class ChatEndpoint {
...
}
http://localhost:8080/chatapp/chatrooms/currentnews
Client Slide: JavaScript for
WebScoket
2014/3/1221
@ServerEndpoint("/chatrooms/{room-name}")
public class ChatEndpoint {
@OnOpen
public void open(Session session,EndpointConfig c,
@PathParam("room-name") String roomName) {
// Add the client to the chat room of their choice ...
}
}
Client Slide: JavaScript for
WebScoket
2014/3/1222
 異常處理
@ServerEndpoint("/testendpoint")
public class TestEndpoint {
...
@OnError
public void error(Session session, Throwable t) {
t.printStackTrace();
...
}
}
Client Slide: JavaScript for
WebScoket
2014/3/1223
 建立連線
 關閉連線
 委派訊息事件
var wsocket = new WebSocket("ws://localhost:8080/dukeetf2/dukeetf");
wsocket.onmessage = onMessage;
function onMessage(evt) {
var arraypv = evt.data.split(",");
document.getElementById("price").innerHTML = arraypv[0];
document.getElementById("volume").innerHTML = arraypv[1];
}
wsocket.close();
Client Slide: JavaScript for
WebScoket
2014/3/1224
 相關事件處理
wsocket.onopen = function () {
setConnected(true);
log('Info: WebSocket connection opened.');
};
wsocket.onmessage = function (event) {
log('Received: ' + event.data);
};
wsocket.onclose = function () {
setConnected(false);
log('Info: WebSocket connection closed.');
};
wsocket.onerror = function (er) {
setConnected(false);
log('Info: WebSocket connection error.‘ + er.data);
};
2014/3/1225
Thanks

More Related Content

What's hot

Networking in Java with NIO and Netty
Networking in Java with NIO and NettyNetworking in Java with NIO and Netty
Networking in Java with NIO and NettyConstantine Slisenka
 
BPF Internals (eBPF)
BPF Internals (eBPF)BPF Internals (eBPF)
BPF Internals (eBPF)Brendan Gregg
 
WebAssembly WASM Introduction Presentation
WebAssembly WASM Introduction PresentationWebAssembly WASM Introduction Presentation
WebAssembly WASM Introduction PresentationBrad Beiermann
 
Slice Recycling Performance and Pitfalls
Slice Recycling Performance and PitfallsSlice Recycling Performance and Pitfalls
Slice Recycling Performance and PitfallsDavid Golden
 
YOW2018 Cloud Performance Root Cause Analysis at Netflix
YOW2018 Cloud Performance Root Cause Analysis at NetflixYOW2018 Cloud Performance Root Cause Analysis at Netflix
YOW2018 Cloud Performance Root Cause Analysis at NetflixBrendan Gregg
 
Blazing Performance with Flame Graphs
Blazing Performance with Flame GraphsBlazing Performance with Flame Graphs
Blazing Performance with Flame GraphsBrendan Gregg
 
NDC14 - Rx와 Functional Reactive Programming으로 고성능 서버 만들기
NDC14 - Rx와 Functional Reactive Programming으로 고성능 서버 만들기NDC14 - Rx와 Functional Reactive Programming으로 고성능 서버 만들기
NDC14 - Rx와 Functional Reactive Programming으로 고성능 서버 만들기Jong Wook Kim
 
Tame the small files problem and optimize data layout for streaming ingestion...
Tame the small files problem and optimize data layout for streaming ingestion...Tame the small files problem and optimize data layout for streaming ingestion...
Tame the small files problem and optimize data layout for streaming ingestion...Flink Forward
 
An Introduction to WebAssembly
An Introduction to WebAssemblyAn Introduction to WebAssembly
An Introduction to WebAssemblyDaniel Budden
 
Flexviews materialized views for my sql
Flexviews materialized views for my sqlFlexviews materialized views for my sql
Flexviews materialized views for my sqlJustin Swanhart
 
Scaling Asterisk with Kamailio
Scaling Asterisk with KamailioScaling Asterisk with Kamailio
Scaling Asterisk with KamailioFred Posner
 
State: You're Doing It Wrong - Alternative Concurrency Paradigms For The JVM
State: You're Doing It Wrong - Alternative Concurrency Paradigms For The JVMState: You're Doing It Wrong - Alternative Concurrency Paradigms For The JVM
State: You're Doing It Wrong - Alternative Concurrency Paradigms For The JVMJonas Bonér
 
Glibc内存管理ptmalloc源代码分析4
Glibc内存管理ptmalloc源代码分析4Glibc内存管理ptmalloc源代码分析4
Glibc内存管理ptmalloc源代码分析4hans511002
 
Introduction to Node js
Introduction to Node jsIntroduction to Node js
Introduction to Node jsAkshay Mathur
 
ClickHouse Query Performance Tips and Tricks, by Robert Hodges, Altinity CEO
ClickHouse Query Performance Tips and Tricks, by Robert Hodges, Altinity CEOClickHouse Query Performance Tips and Tricks, by Robert Hodges, Altinity CEO
ClickHouse Query Performance Tips and Tricks, by Robert Hodges, Altinity CEOAltinity Ltd
 
Practical non blocking microservices in java 8
Practical non blocking microservices in java 8Practical non blocking microservices in java 8
Practical non blocking microservices in java 8Michal Balinski
 

What's hot (20)

Iocp advanced
Iocp advancedIocp advanced
Iocp advanced
 
Networking in Java with NIO and Netty
Networking in Java with NIO and NettyNetworking in Java with NIO and Netty
Networking in Java with NIO and Netty
 
Introduction to Data Oriented Design
Introduction to Data Oriented DesignIntroduction to Data Oriented Design
Introduction to Data Oriented Design
 
BPF Internals (eBPF)
BPF Internals (eBPF)BPF Internals (eBPF)
BPF Internals (eBPF)
 
WebAssembly WASM Introduction Presentation
WebAssembly WASM Introduction PresentationWebAssembly WASM Introduction Presentation
WebAssembly WASM Introduction Presentation
 
Slice Recycling Performance and Pitfalls
Slice Recycling Performance and PitfallsSlice Recycling Performance and Pitfalls
Slice Recycling Performance and Pitfalls
 
YOW2018 Cloud Performance Root Cause Analysis at Netflix
YOW2018 Cloud Performance Root Cause Analysis at NetflixYOW2018 Cloud Performance Root Cause Analysis at Netflix
YOW2018 Cloud Performance Root Cause Analysis at Netflix
 
Blazing Performance with Flame Graphs
Blazing Performance with Flame GraphsBlazing Performance with Flame Graphs
Blazing Performance with Flame Graphs
 
NDC14 - Rx와 Functional Reactive Programming으로 고성능 서버 만들기
NDC14 - Rx와 Functional Reactive Programming으로 고성능 서버 만들기NDC14 - Rx와 Functional Reactive Programming으로 고성능 서버 만들기
NDC14 - Rx와 Functional Reactive Programming으로 고성능 서버 만들기
 
InnoDB Locking Explained with Stick Figures
InnoDB Locking Explained with Stick FiguresInnoDB Locking Explained with Stick Figures
InnoDB Locking Explained with Stick Figures
 
Tame the small files problem and optimize data layout for streaming ingestion...
Tame the small files problem and optimize data layout for streaming ingestion...Tame the small files problem and optimize data layout for streaming ingestion...
Tame the small files problem and optimize data layout for streaming ingestion...
 
An Introduction to WebAssembly
An Introduction to WebAssemblyAn Introduction to WebAssembly
An Introduction to WebAssembly
 
Flexviews materialized views for my sql
Flexviews materialized views for my sqlFlexviews materialized views for my sql
Flexviews materialized views for my sql
 
Scaling Asterisk with Kamailio
Scaling Asterisk with KamailioScaling Asterisk with Kamailio
Scaling Asterisk with Kamailio
 
State: You're Doing It Wrong - Alternative Concurrency Paradigms For The JVM
State: You're Doing It Wrong - Alternative Concurrency Paradigms For The JVMState: You're Doing It Wrong - Alternative Concurrency Paradigms For The JVM
State: You're Doing It Wrong - Alternative Concurrency Paradigms For The JVM
 
Glibc内存管理ptmalloc源代码分析4
Glibc内存管理ptmalloc源代码分析4Glibc内存管理ptmalloc源代码分析4
Glibc内存管理ptmalloc源代码分析4
 
Introduction to Node js
Introduction to Node jsIntroduction to Node js
Introduction to Node js
 
Caching Strategies
Caching StrategiesCaching Strategies
Caching Strategies
 
ClickHouse Query Performance Tips and Tricks, by Robert Hodges, Altinity CEO
ClickHouse Query Performance Tips and Tricks, by Robert Hodges, Altinity CEOClickHouse Query Performance Tips and Tricks, by Robert Hodges, Altinity CEO
ClickHouse Query Performance Tips and Tricks, by Robert Hodges, Altinity CEO
 
Practical non blocking microservices in java 8
Practical non blocking microservices in java 8Practical non blocking microservices in java 8
Practical non blocking microservices in java 8
 

Viewers also liked

淺談Html5及建立完整 web socket 應用觀念
淺談Html5及建立完整 web socket 應用觀念淺談Html5及建立完整 web socket 應用觀念
淺談Html5及建立完整 web socket 應用觀念志賢 黃
 
TypeScript 開發實戰:開發即時互動的 html5 websocket 聊天室應用程式
TypeScript 開發實戰:開發即時互動的 html5 websocket 聊天室應用程式TypeScript 開發實戰:開發即時互動的 html5 websocket 聊天室應用程式
TypeScript 開發實戰:開發即時互動的 html5 websocket 聊天室應用程式Will Huang
 
PHP 應用之一 socket funion : 偽 WEB Server
PHP 應用之一 socket funion : 偽 WEB ServerPHP 應用之一 socket funion : 偽 WEB Server
PHP 應用之一 socket funion : 偽 WEB Server志賢 黃
 
利用Signalr打造即時通訊@Tech day geek
利用Signalr打造即時通訊@Tech day geek利用Signalr打造即時通訊@Tech day geek
利用Signalr打造即時通訊@Tech day geekJohnson Gau
 
高效能執行緒
高效能執行緒高效能執行緒
高效能執行緒Rick Wu
 
愛愛上雲端
愛愛上雲端愛愛上雲端
愛愛上雲端志賢 黃
 
醜簡報是怎樣煉成的:摧毀一份簡報的四個方式
醜簡報是怎樣煉成的:摧毀一份簡報的四個方式醜簡報是怎樣煉成的:摧毀一份簡報的四個方式
醜簡報是怎樣煉成的:摧毀一份簡報的四個方式Jian-Ming Ke
 
使用Javascript及HTML5打造協同運作系統
使用Javascript及HTML5打造協同運作系統使用Javascript及HTML5打造協同運作系統
使用Javascript及HTML5打造協同運作系統Hsu Ping Feng
 
Ingesting Drone Data into Big Data Platforms
Ingesting Drone Data into Big Data Platforms Ingesting Drone Data into Big Data Platforms
Ingesting Drone Data into Big Data Platforms Timothy Spann
 
How to Make Awesome SlideShares: Tips & Tricks
How to Make Awesome SlideShares: Tips & TricksHow to Make Awesome SlideShares: Tips & Tricks
How to Make Awesome SlideShares: Tips & TricksSlideShare
 
Getting Started With SlideShare
Getting Started With SlideShareGetting Started With SlideShare
Getting Started With SlideShareSlideShare
 

Viewers also liked (11)

淺談Html5及建立完整 web socket 應用觀念
淺談Html5及建立完整 web socket 應用觀念淺談Html5及建立完整 web socket 應用觀念
淺談Html5及建立完整 web socket 應用觀念
 
TypeScript 開發實戰:開發即時互動的 html5 websocket 聊天室應用程式
TypeScript 開發實戰:開發即時互動的 html5 websocket 聊天室應用程式TypeScript 開發實戰:開發即時互動的 html5 websocket 聊天室應用程式
TypeScript 開發實戰:開發即時互動的 html5 websocket 聊天室應用程式
 
PHP 應用之一 socket funion : 偽 WEB Server
PHP 應用之一 socket funion : 偽 WEB ServerPHP 應用之一 socket funion : 偽 WEB Server
PHP 應用之一 socket funion : 偽 WEB Server
 
利用Signalr打造即時通訊@Tech day geek
利用Signalr打造即時通訊@Tech day geek利用Signalr打造即時通訊@Tech day geek
利用Signalr打造即時通訊@Tech day geek
 
高效能執行緒
高效能執行緒高效能執行緒
高效能執行緒
 
愛愛上雲端
愛愛上雲端愛愛上雲端
愛愛上雲端
 
醜簡報是怎樣煉成的:摧毀一份簡報的四個方式
醜簡報是怎樣煉成的:摧毀一份簡報的四個方式醜簡報是怎樣煉成的:摧毀一份簡報的四個方式
醜簡報是怎樣煉成的:摧毀一份簡報的四個方式
 
使用Javascript及HTML5打造協同運作系統
使用Javascript及HTML5打造協同運作系統使用Javascript及HTML5打造協同運作系統
使用Javascript及HTML5打造協同運作系統
 
Ingesting Drone Data into Big Data Platforms
Ingesting Drone Data into Big Data Platforms Ingesting Drone Data into Big Data Platforms
Ingesting Drone Data into Big Data Platforms
 
How to Make Awesome SlideShares: Tips & Tricks
How to Make Awesome SlideShares: Tips & TricksHow to Make Awesome SlideShares: Tips & Tricks
How to Make Awesome SlideShares: Tips & Tricks
 
Getting Started With SlideShare
Getting Started With SlideShareGetting Started With SlideShare
Getting Started With SlideShare
 

Similar to Java API for WebSocket 實作介紹

Real time web实时信息流推送
Real time web实时信息流推送Real time web实时信息流推送
Real time web实时信息流推送yongboy
 
Real-Time Web实时信息流推送
Real-Time Web实时信息流推送Real-Time Web实时信息流推送
Real-Time Web实时信息流推送yongboy
 
Spring 2.0 技術手冊第七章 - Spring Web MVC 框架
Spring 2.0 技術手冊第七章 - Spring Web MVC 框架Spring 2.0 技術手冊第七章 - Spring Web MVC 框架
Spring 2.0 技術手冊第七章 - Spring Web MVC 框架Justin Lin
 
real-time Web的運用
real-time Web的運用real-time Web的運用
real-time Web的運用Robin Su
 
IoTDB Quick Start
IoTDB Quick StartIoTDB Quick Start
IoTDB Quick StartJialinQiao
 
实时Web的前世今生未来
实时Web的前世今生未来实时Web的前世今生未来
实时Web的前世今生未来RolfZhang
 
Node Web开发实战
Node Web开发实战Node Web开发实战
Node Web开发实战fengmk2
 
高性能并发Web服务器实现核心内幕
高性能并发Web服务器实现核心内幕高性能并发Web服务器实现核心内幕
高性能并发Web服务器实现核心内幕ideawu
 
Node Web开发实战
Node Web开发实战Node Web开发实战
Node Web开发实战fengmk2
 
Non-MVC Web Framework
Non-MVC Web FrameworkNon-MVC Web Framework
Non-MVC Web FrameworkFred Chien
 
Asp.net mvc 4 web api 開發簡介
Asp.net mvc 4 web api 開發簡介Asp.net mvc 4 web api 開發簡介
Asp.net mvc 4 web api 開發簡介Gelis Wu
 
Java技术讲座 网络编程
Java技术讲座 网络编程Java技术讲座 网络编程
Java技术讲座 网络编程xujie
 
Real World ASP.NET MVC
Real World ASP.NET MVCReal World ASP.NET MVC
Real World ASP.NET MVCjeffz
 
GlassFish特性介绍
GlassFish特性介绍GlassFish特性介绍
GlassFish特性介绍Jim Jiang
 
Node.js长连接开发实践
Node.js长连接开发实践Node.js长连接开发实践
Node.js长连接开发实践longhao
 
Servlet & JSP 教學手冊第二版 - 課後練習解答
Servlet & JSP 教學手冊第二版 - 課後練習解答Servlet & JSP 教學手冊第二版 - 課後練習解答
Servlet & JSP 教學手冊第二版 - 課後練習解答Justin Lin
 
非常靠谱 Html 5
非常靠谱 Html 5 非常靠谱 Html 5
非常靠谱 Html 5 Tony Deng
 
從SOA到REST -- Web Service、WCF、WebAPI的應用情境
從SOA到REST -- Web Service、WCF、WebAPI的應用情境從SOA到REST -- Web Service、WCF、WebAPI的應用情境
從SOA到REST -- Web Service、WCF、WebAPI的應用情境MIS2000 Lab.
 

Similar to Java API for WebSocket 實作介紹 (20)

Real time web实时信息流推送
Real time web实时信息流推送Real time web实时信息流推送
Real time web实时信息流推送
 
Real-Time Web实时信息流推送
Real-Time Web实时信息流推送Real-Time Web实时信息流推送
Real-Time Web实时信息流推送
 
Spring 2.0 技術手冊第七章 - Spring Web MVC 框架
Spring 2.0 技術手冊第七章 - Spring Web MVC 框架Spring 2.0 技術手冊第七章 - Spring Web MVC 框架
Spring 2.0 技術手冊第七章 - Spring Web MVC 框架
 
real-time Web的運用
real-time Web的運用real-time Web的運用
real-time Web的運用
 
IoTDB Quick Start
IoTDB Quick StartIoTDB Quick Start
IoTDB Quick Start
 
实时Web的前世今生未来
实时Web的前世今生未来实时Web的前世今生未来
实时Web的前世今生未来
 
Node Web开发实战
Node Web开发实战Node Web开发实战
Node Web开发实战
 
高性能并发Web服务器实现核心内幕
高性能并发Web服务器实现核心内幕高性能并发Web服务器实现核心内幕
高性能并发Web服务器实现核心内幕
 
Node Web开发实战
Node Web开发实战Node Web开发实战
Node Web开发实战
 
Html5
Html5Html5
Html5
 
Non-MVC Web Framework
Non-MVC Web FrameworkNon-MVC Web Framework
Non-MVC Web Framework
 
Asp.net mvc 4 web api 開發簡介
Asp.net mvc 4 web api 開發簡介Asp.net mvc 4 web api 開發簡介
Asp.net mvc 4 web api 開發簡介
 
Java技术讲座 网络编程
Java技术讲座 网络编程Java技术讲座 网络编程
Java技术讲座 网络编程
 
Webrtc
WebrtcWebrtc
Webrtc
 
Real World ASP.NET MVC
Real World ASP.NET MVCReal World ASP.NET MVC
Real World ASP.NET MVC
 
GlassFish特性介绍
GlassFish特性介绍GlassFish特性介绍
GlassFish特性介绍
 
Node.js长连接开发实践
Node.js长连接开发实践Node.js长连接开发实践
Node.js长连接开发实践
 
Servlet & JSP 教學手冊第二版 - 課後練習解答
Servlet & JSP 教學手冊第二版 - 課後練習解答Servlet & JSP 教學手冊第二版 - 課後練習解答
Servlet & JSP 教學手冊第二版 - 課後練習解答
 
非常靠谱 Html 5
非常靠谱 Html 5 非常靠谱 Html 5
非常靠谱 Html 5
 
從SOA到REST -- Web Service、WCF、WebAPI的應用情境
從SOA到REST -- Web Service、WCF、WebAPI的應用情境從SOA到REST -- Web Service、WCF、WebAPI的應用情境
從SOA到REST -- Web Service、WCF、WebAPI的應用情境
 

More from My own sweet home!

Sencha touch 2 訓練課程 3 phonegap整合
Sencha touch 2 訓練課程 3 phonegap整合Sencha touch 2 訓練課程 3 phonegap整合
Sencha touch 2 訓練課程 3 phonegap整合My own sweet home!
 
自造世代下的新創模式
自造世代下的新創模式自造世代下的新創模式
自造世代下的新創模式My own sweet home!
 
Sencha touch 2 訓練課程 2 android環境建置
Sencha touch 2 訓練課程 2 android環境建置Sencha touch 2 訓練課程 2 android環境建置
Sencha touch 2 訓練課程 2 android環境建置My own sweet home!
 
Sencha touch 2 訓練課程 1 建置專案環境
Sencha touch 2 訓練課程 1 建置專案環境Sencha touch 2 訓練課程 1 建置專案環境
Sencha touch 2 訓練課程 1 建置專案環境My own sweet home!
 
Ch3 文創產業網路行銷_Ch3-露天拍賣入門與實務 商品管理
Ch3   文創產業網路行銷_Ch3-露天拍賣入門與實務 商品管理Ch3   文創產業網路行銷_Ch3-露天拍賣入門與實務 商品管理
Ch3 文創產業網路行銷_Ch3-露天拍賣入門與實務 商品管理My own sweet home!
 
文創產業網路行銷_Ch1 1 - 常用服務申請與使用
文創產業網路行銷_Ch1 1 - 常用服務申請與使用文創產業網路行銷_Ch1 1 - 常用服務申請與使用
文創產業網路行銷_Ch1 1 - 常用服務申請與使用My own sweet home!
 
文創產業網路行銷_Ch2 露天拍賣入門與實務 基本操作
文創產業網路行銷_Ch2   露天拍賣入門與實務 基本操作文創產業網路行銷_Ch2   露天拍賣入門與實務 基本操作
文創產業網路行銷_Ch2 露天拍賣入門與實務 基本操作My own sweet home!
 
文創產業網路行銷_Ch1 課程介紹與準備
文創產業網路行銷_Ch1   課程介紹與準備文創產業網路行銷_Ch1   課程介紹與準備
文創產業網路行銷_Ch1 課程介紹與準備My own sweet home!
 
電子商務軟體 管理與實務 Course Introduction
電子商務軟體 管理與實務 Course Introduction電子商務軟體 管理與實務 Course Introduction
電子商務軟體 管理與實務 Course IntroductionMy own sweet home!
 
行動商務 - PhoneGapBuild and Upto Market
行動商務 - PhoneGapBuild and Upto Market行動商務 - PhoneGapBuild and Upto Market
行動商務 - PhoneGapBuild and Upto MarketMy own sweet home!
 
行動商務實務 - PhoneGap Advance
行動商務實務 - PhoneGap Advance行動商務實務 - PhoneGap Advance
行動商務實務 - PhoneGap AdvanceMy own sweet home!
 
行動商務實務 - PhoneGap Basic
行動商務實務 - PhoneGap Basic 行動商務實務 - PhoneGap Basic
行動商務實務 - PhoneGap Basic My own sweet home!
 
Apache cordova 開發環境建置
Apache cordova 開發環境建置Apache cordova 開發環境建置
Apache cordova 開發環境建置My own sweet home!
 
行動開店 交易與支付 APPZ - 101-1學期 行動商務管理實務 第六週
行動開店   交易與支付 APPZ - 101-1學期 行動商務管理實務 第六週行動開店   交易與支付 APPZ - 101-1學期 行動商務管理實務 第六週
行動開店 交易與支付 APPZ - 101-1學期 行動商務管理實務 第六週My own sweet home!
 
Web based mobile devlopment 快速簡介
Web based mobile devlopment 快速簡介Web based mobile devlopment 快速簡介
Web based mobile devlopment 快速簡介My own sweet home!
 
開放原始碼 Ch3.2 mobile - oss - oss行動領域-2 (ver1.0)
開放原始碼 Ch3.2  mobile - oss - oss行動領域-2 (ver1.0)開放原始碼 Ch3.2  mobile - oss - oss行動領域-2 (ver1.0)
開放原始碼 Ch3.2 mobile - oss - oss行動領域-2 (ver1.0)My own sweet home!
 

More from My own sweet home! (20)

Sencha touch 2 訓練課程 3 phonegap整合
Sencha touch 2 訓練課程 3 phonegap整合Sencha touch 2 訓練課程 3 phonegap整合
Sencha touch 2 訓練課程 3 phonegap整合
 
自造世代下的新創模式
自造世代下的新創模式自造世代下的新創模式
自造世代下的新創模式
 
物聯網 雲端智慧家庭
物聯網 雲端智慧家庭物聯網 雲端智慧家庭
物聯網 雲端智慧家庭
 
Sencha touch 2 訓練課程 2 android環境建置
Sencha touch 2 訓練課程 2 android環境建置Sencha touch 2 訓練課程 2 android環境建置
Sencha touch 2 訓練課程 2 android環境建置
 
Sencha touch 2 訓練課程 1 建置專案環境
Sencha touch 2 訓練課程 1 建置專案環境Sencha touch 2 訓練課程 1 建置專案環境
Sencha touch 2 訓練課程 1 建置專案環境
 
Ch3 文創產業網路行銷_Ch3-露天拍賣入門與實務 商品管理
Ch3   文創產業網路行銷_Ch3-露天拍賣入門與實務 商品管理Ch3   文創產業網路行銷_Ch3-露天拍賣入門與實務 商品管理
Ch3 文創產業網路行銷_Ch3-露天拍賣入門與實務 商品管理
 
文創產業網路行銷_Ch1 1 - 常用服務申請與使用
文創產業網路行銷_Ch1 1 - 常用服務申請與使用文創產業網路行銷_Ch1 1 - 常用服務申請與使用
文創產業網路行銷_Ch1 1 - 常用服務申請與使用
 
文創產業網路行銷_Ch2 露天拍賣入門與實務 基本操作
文創產業網路行銷_Ch2   露天拍賣入門與實務 基本操作文創產業網路行銷_Ch2   露天拍賣入門與實務 基本操作
文創產業網路行銷_Ch2 露天拍賣入門與實務 基本操作
 
文創產業網路行銷_Ch1 課程介紹與準備
文創產業網路行銷_Ch1   課程介紹與準備文創產業網路行銷_Ch1   課程介紹與準備
文創產業網路行銷_Ch1 課程介紹與準備
 
電子商務軟體 管理與實務 Course Introduction
電子商務軟體 管理與實務 Course Introduction電子商務軟體 管理與實務 Course Introduction
電子商務軟體 管理與實務 Course Introduction
 
行動商務 - PhoneGapBuild and Upto Market
行動商務 - PhoneGapBuild and Upto Market行動商務 - PhoneGapBuild and Upto Market
行動商務 - PhoneGapBuild and Upto Market
 
行動商務實務 - PhoneGap Advance
行動商務實務 - PhoneGap Advance行動商務實務 - PhoneGap Advance
行動商務實務 - PhoneGap Advance
 
行動商務實務 - PhoneGap Basic
行動商務實務 - PhoneGap Basic 行動商務實務 - PhoneGap Basic
行動商務實務 - PhoneGap Basic
 
JQuery Mobile UI
JQuery Mobile UIJQuery Mobile UI
JQuery Mobile UI
 
Apache cordova 開發環境建置
Apache cordova 開發環境建置Apache cordova 開發環境建置
Apache cordova 開發環境建置
 
行動開店 交易與支付 APPZ - 101-1學期 行動商務管理實務 第六週
行動開店   交易與支付 APPZ - 101-1學期 行動商務管理實務 第六週行動開店   交易與支付 APPZ - 101-1學期 行動商務管理實務 第六週
行動開店 交易與支付 APPZ - 101-1學期 行動商務管理實務 第六週
 
創業從零開始
創業從零開始創業從零開始
創業從零開始
 
行動技術開發概論
行動技術開發概論行動技術開發概論
行動技術開發概論
 
Web based mobile devlopment 快速簡介
Web based mobile devlopment 快速簡介Web based mobile devlopment 快速簡介
Web based mobile devlopment 快速簡介
 
開放原始碼 Ch3.2 mobile - oss - oss行動領域-2 (ver1.0)
開放原始碼 Ch3.2  mobile - oss - oss行動領域-2 (ver1.0)開放原始碼 Ch3.2  mobile - oss - oss行動領域-2 (ver1.0)
開放原始碼 Ch3.2 mobile - oss - oss行動領域-2 (ver1.0)
 

Java API for WebSocket 實作介紹

  • 2. 大綱 2014/3/122  簡介  類型  JAVA 平台  Server Side: Java Servlet  Client Slide: JavaScript for WebScoket
  • 3. 簡介 2014/3/123  WebSocket 是種通訊協定,透過TCP 通訊協定提 供全工雙向通訊資料交換。  針對WWW透過HTTP建立資料交換的需求。  JSR-356  Java API for WebSocket  實作 RFC6455: The WebSocket Protocol  Apache Tomcat 8 支援  主流的瀏覽器都支援WebSocket且提供JavaScript API
  • 4. 簡介 2014/3/124  為何要採用 WebScoket?  現有 HTTP 屬於短連接,用完即關閉。屬於無狀態 保存的通訊協定。  實務上需要能夠即時傳遞資料。  過去即時性資料交換,大多採用輪詢的方式。定時向 對方建立連線詢問。效能差,無法即時。  適用:  股市行情即時  通訊軟體,Line等。  訊息即時傳遞需要。
  • 5. 類型 2014/3/125  WebSocket Application  Server: 發佈 WebSoocket Endpoint 提供連線端 URIs  Client: 使用 endpoint URIs來向 server 建立連線請求。  WebSocket 通訊協定在完成建立連線後既已完成雙 方對稱狀態。任一方皆可發送與接受訊息。並且可以 隨意關閉連線。 Client ServerClient Client
  • 6. 類型 2014/3/126  WebSocket 通訊協定  Handshake: client 送出 WebSocket Endpoint URIs 進行交握機制來建立連線請求。交握機制是基於 HTTP為基礎架構上完成。  Data trandfer GET /path/to/websocket/endpoint HTTP/1.1 Host: localhost Upgrade: websocket Connection: Upgrade Sec-WebSocket-Key: xqBt3ImNzJbYqRINxEFlkg== Origin: http://localhost Sec-WebSocket-Version: 13 HTTP/1.1 101 Switching Protocols Upgrade: websocket Connection: Upgrade Sec-WebSocket-Accept: K7DJLdLooIwIG/MOpvWFB3y3FE8 =
  • 7. 類型 2014/3/127  支援的資料內容  文字訊息 (以UTF-8編碼)  二進制訊息,圖片、聲音或物件等。  控制框格式  Close  Ping  Pong  Ping 的回應  Ping 與 Pong 都是含有資料
  • 8. 類型 2014/3/128  何謂 WebSocket Endpoint URIs?  ws://host:port/path?query  wss://host:port/path?query  Port 部分是可省略,預設則是80或443。  加密模式 HTTPS對應就是 wss
  • 9. JAVA 平台 2014/3/129  Java API for WebSocket (JSR-356)  提供規範規格建立與佈署WebSocket endpoints的 Web 應用程式  WebSocket client API 規範規格提供開發應用程式向 遠端WebSocket endpoints 存取操作  javax.websocket.server 套件  提供相關類別與介面建立與設定 server 端 endpoints  javax.websocket 套件  提供 client 與 server endpoints 共通介面與類別
  • 10. JAVA 平台 2014/3/1210  WebSocket endpoints 是 javax.websocket.Endpoint 的類別的物件實體。  JSR-356 提供兩種endpoints方式來使用API  Programmatic endpoints  繼承 Endpoint類別使用相關方法  Annotated endpoint  使用 annotations 來操作方法
  • 11. Server Side: Java Servlet 2014/3/1211  Programmatic endpoints public class EchoEndpoint extends Endpoint { @Override public void onOpen(final Session session, EndpointConfig config) { session.addMessageHandler(new MessageHandler.Whole<String>() @Override public void onMessage(String msg) { try { session.getBasicRemote().sendText(msg); } catch (IOException e) { ... } } }); } }
  • 12. Server Side: Java Servlet 2014/3/1212  session 參數物件  代表連線的雙方連線狀態  佈署方式  佈署後,其endpoint 如下 ServerEndpointConfig.Builder.create(EchoEndpoint.class, "/echo").build(); ws://localhost:8080/echoapp/echo
  • 13. Server Side: Java Servlet 2014/3/1213  Annotated endpoint @ServerEndpoint("/echo") public class EchoEndpoint { @OnMessage public void onMessage(Session session, String msg) { try { session.getBasicRemote().sendText(msg); } catch (IOException e) { ... } } }
  • 14. Server Side: Java Servlet 2014/3/1214  相關方法 Annotatio n Event 說明 OnOpen 連線已經建立與 開啟 @OnOpen public void open(Session session, EndpointConfig conf) { } OnMessa ge 收到訊息 @OnMessage public void message (Session session, String msg) { } OnError 連線錯誤 @OnError public void error(Session session, Throwable error) { } OnClose 連線已關閉 @OnClose public void close(Session session, CloseReason reason) { }
  • 15. Client Slide: JavaScript for WebScoket 2014/3/1215  送收訊息  使用 Session 取得 RemoteEndpoint物件  Session.getBasicRemote()  取得 RemoteEndpoint.Basic 物件的 blocking 方法  Session.getAsyncRemote()  取得 RemoteEndpoint.Async 物件的non-blocking方法
  • 16. Client Slide: JavaScript for WebScoket 2014/3/1216  送出訊息  文字訊息  void RemoteEndpoint.Basic.sendText(String text)  二進制訊息  void RemoteEndpoint.Basic.sendBinary(ByteBuffer data)  Ping 訊息  void RemoteEndpoint.sendPing(ByteBuffer appData)  Pong訊息  void RemoteEndpoint.sendPong(ByteBuffer appData)
  • 17. Client Slide: JavaScript for WebScoket 2014/3/1217  取得全部已經連線所有session  session.getOpenSessions() @ServerEndpoint("/echoall") public class EchoAllEndpoint { @OnMessage public void onMessage(Session session, String msg) { try { for (Session sess : session.getOpenSessions()) { if (sess.isOpen()) sess.getBasicRemote().sendText(msg); } } catch (IOException e) { ... } } }
  • 18. Client Slide: JavaScript for WebScoket 2014/3/1218  接收訊息類型 @ServerEndpoint("/receive") public class ReceiveEndpoint { @OnMessage public void textMessage(Session session, String msg) { System.out.println("Text message: " + msg); } @OnMessage public void binaryMessage(Session session, ByteBuffer msg) { System.out.println("Binary message: " + msg.toString()); } @OnMessage public void pongMessage(Session session, PongMessage msg) { System.out.println("Pong message: " + msg.getApplicationData().toString()); } }
  • 19. Client Slide: JavaScript for WebScoket 2014/3/1219  處理 client 端狀態 @ServerEndpoint("/delayedecho") public class DelayedEchoEndpoint { @OnOpen public void open(Session session) { session.getUserProperties().put("previousMsg", " "); } @OnMessage public void message(Session session, String msg) { String prev = (String) session.getUserProperties().get("previousMsg"); session.getUserProperties().put("previousMsg", msg); try { session.getBasicRemote().sendText(prev); } catch (IOException e) { ... } } }
  • 20. Client Slide: JavaScript for WebScoket 2014/3/1220  其他  Encoders與 Decoders  處理資料型別的轉換  Java Object to JSON/XML  Path 參數  把 URI 以參數方式處理 @ServerEndpoint("/chatrooms/{room-name}") public class ChatEndpoint { ... } http://localhost:8080/chatapp/chatrooms/currentnews
  • 21. Client Slide: JavaScript for WebScoket 2014/3/1221 @ServerEndpoint("/chatrooms/{room-name}") public class ChatEndpoint { @OnOpen public void open(Session session,EndpointConfig c, @PathParam("room-name") String roomName) { // Add the client to the chat room of their choice ... } }
  • 22. Client Slide: JavaScript for WebScoket 2014/3/1222  異常處理 @ServerEndpoint("/testendpoint") public class TestEndpoint { ... @OnError public void error(Session session, Throwable t) { t.printStackTrace(); ... } }
  • 23. Client Slide: JavaScript for WebScoket 2014/3/1223  建立連線  關閉連線  委派訊息事件 var wsocket = new WebSocket("ws://localhost:8080/dukeetf2/dukeetf"); wsocket.onmessage = onMessage; function onMessage(evt) { var arraypv = evt.data.split(","); document.getElementById("price").innerHTML = arraypv[0]; document.getElementById("volume").innerHTML = arraypv[1]; } wsocket.close();
  • 24. Client Slide: JavaScript for WebScoket 2014/3/1224  相關事件處理 wsocket.onopen = function () { setConnected(true); log('Info: WebSocket connection opened.'); }; wsocket.onmessage = function (event) { log('Received: ' + event.data); }; wsocket.onclose = function () { setConnected(false); log('Info: WebSocket connection closed.'); }; wsocket.onerror = function (er) { setConnected(false); log('Info: WebSocket connection error.‘ + er.data); };