糯米文學吧

位置:首頁 > 計算機 > java語言

Java中Websocket使用實例解析

java語言2.01W

在 WebSocket API,瀏覽器和服務器只需要要做一個握手的動作,然後,瀏覽器和服務器之間就形成了一條快速通道。兩者之間就直接可以數據互相傳送。下面小編給大家介紹Java中Websocket使用實例解析,歡迎閲讀!

Java中Websocket使用實例解析
  Java中Websocket使用實例解析

運行環境

客户端

實現了websocket的瀏覽器



Chrome Supported in version 4+
Firefox Supported in version 4+
Internet Explorer Supported in version 10+
Opera Supported in version 10+
Safari Supported in version 5+

服務端

依賴

<dependency>

<groupId>at</groupId>

<artifactId>tomcat-websocket-api</artifactId>

<version>7.0.47</version>

<scope>provided</scope>

</dependency>

<dependency>

<groupId>javax</groupId>

<artifactId>javaee-api</artifactId>

<version>7.0</version>

<scope>provided</scope>

</dependency>

注意:早前業界沒有統一的標準,各服務器都有各自的實現,現在J2EE7的JSR356已經定義了統一的標準,請儘量使用支持最新通用標準的服務器。

我是用的Tomcat 7.0.57 + Java7

必須是Tomcat 7.0.47以上

ps:最早我們是用的Tomcat 7自帶的實現,後來要升級Tomcat 8,結果原來的實現方式在Tomcat 8不支持了,就只好切換到支持Websocket 1.0版本的Tomcat了。

主流的java web服務器都有支持JSR365標準的版本了,請自行Google。

用nginx做反向代理的需要注意啦,socket請求需要做特殊配置的,切記!

Tomcat的處理方式建議修改為NIO的方式,同時修改連接數到合適的參數,請自行Google!

服務端不需要在中做額外的配置,Tomcat啟動後就可以直接連接了。

實現

import ionUtils;

import ;

import actory;

import ocket.*;

import Param;

import erEndpoint;

/**

* 功能説明:websocket處理類, 使用J2EE7的標準

* 切忌直接在該連接處理類中加入業務處理代碼

*/

//relationId和userCode是我的業務標識參數,是連接的'路徑,可以自行定義

@ServerEndpoint("/{relationId}/{userCode}")

public class WebsocketEndPoint {

private static Log log = og(s);

/**

* 打開連接時觸發

* @param relationId

* @param userCode

* @param session

*/

@OnOpen

public void onOpen(@PathParam("relationId") String relationId,

@PathParam("userCode") int userCode,

Session session){

("Websocket Start Connecting: " + ey(relationId, userCode));

(relationId, userCode, session);

}

/**

* 收到客户端消息時觸發

* @param relationId

* @param userCode

* @param message

* @return

*/

@OnMessage

public String onMessage(@PathParam("relationId") String relationId,

@PathParam("userCode") int userCode,

String message) {

return "Got your message (" + message + ")ks !";

}

/**

* 異常時觸發

* @param relationId

* @param userCode

* @param session

*/

@OnError

public void onError(@PathParam("relationId") String relationId,

@PathParam("userCode") int userCode,

Throwable throwable,

Session session) {

("Websocket Connection Exception: " + ey(relationId, userCode));

(essage(), throwable);

ve(relationId, userCode);

}

/**

* 關閉連接時觸發

* @param relationId

* @param userCode

* @param session

*/

@OnClose

public void onClose(@PathParam("relationId") String relationId,

@PathParam("userCode") int userCode,

Session session) {

("Websocket Close Connection: " + ey(relationId, userCode));

ve(relationId, userCode);

}

}

工具類用來存儲唯一key和連接

這個是我業務的需要,我的業務是服務器有對應動作觸發時,推送數據到客户端,沒有接收客户端數據的操作。

import ion;

import ;

import urrentHashMap;

/**

* 功能説明:用來存儲業務定義的sessionId和連接的對應關係

* 利用業務邏輯中組裝的sessionId獲取有效連接後進行後續操作

*/

public class SessionUtils {

public static Map clients = new ConcurrentHashMap<>();

public static void put(String relationId, int userCode, Session session){

(getKey(relationId, userCode), session);

}

public static Session get(String relationId, int userCode){

return (getKey(relationId, userCode));

}

public static void remove(String relationId, int userCode){

ve(getKey(relationId, userCode));

}

/**

* 判斷是否有連接

* @param relationId

* @param userCode

* @return

*/

public static boolean hasConnection(String relationId, int userCode) {

return ainsKey(getKey(relationId, userCode));

}

/**

* 組裝唯一識別的key

* @param relationId

* @param userCode

* @return

*/

public static String getKey(String relationId, int userCode) {

return relationId + "_" + userCode;

}

}

推送數據到客户端

在其他業務方法中調用

/**

* 將數據傳回客户端

* 異步的方式

* @param relationId

* @param userCode

* @param message

*/

public void broadcast(String relationId, int userCode, String message) {

if (onnection(relationId, userCode)) {

(relationId, userCode)syncRemote()Text(message);

} else {

throw new NullPointerException(ey(relationId, userCode) + " Connection does not exist");

}

}

我是使用異步的方法推送數據,還有同步的方法

客户端代碼

var webSocket = null;

var tryTime = 0;

$(function () {

initSocket();

foreunload = function () {

//離開頁面時的其他操作

};

});

/**

* 初始化websocket,建立連接

*/

function initSocket() {

if (!ocket) {

alert("您的瀏覽器不支持websocket!");

return false;

}

webSocket = new WebSocket("ws://" + relationId + "/" + userCode);

// 收到服務端消息

ssage = function (msg) {

(msg);

};

// 異常

ror = function (event) {

(event);

};

// 建立連接

en = function (event) {

(event);

};

// 斷線重連

ose = function () {

// 重試10次,每次之間間隔10秒

if (tryTime < 10) {

setTimeout(function () {

webSocket = null;

tryTime++;

initSocket();

}, 500);

} else {

tryTime = 0;

}

};

}

其他調試工具

Java實現一個websocket的客户端

 依賴:

<dependency>

<groupId>-websocket</groupId>

<artifactId>Java-WebSocket</artifactId>

<version>1.3.0</version>

</dependency>

代碼:

import ception;

import ntEndpoint;

import ror;

import ssage;

import en;

import ion;

@ClientEndpoint

public class MyClient {

@OnOpen

public void onOpen(Session session) {

tln("Connected to endpoint: " + asicRemote());

try {

asicRemote()Text("Hello");

} catch (IOException ex) {

}

}

@OnMessage

public void onMessage(String message) {

tln(message);

}

@OnError

public void onError(Throwable t) {

tStackTrace();

}

}

import eredReader;

import ception;

import tStreamReader;

import ;

import ainerProvider;

import oymentException;

import ion;

import ocketContainer;

public class MyClientApp {

public Session session;

protected void start()

{

WebSocketContainer container = ebSocketContainer();

String uri = "ws://";

tln("Connecting to " + uri);

try {

session = ectToServer(s, te(uri));

} catch (DeploymentException e) {

tStackTrace();

} catch (IOException e) {

tStackTrace();

}

}

public static void main(String args[]){

MyClientApp client = new MyClientApp();

t();

BufferedReader br = new BufferedReader(new InputStreamReader());

String input = "";

try {

do{

input = Line();

if(!ls("exit"))

asicRemote()Text(input);

}while(!ls("exit"));

} catch (IOException e) {

// TODO Auto-generated catch block

tStackTrace();

}

}

}

chrome安裝一個websocket客户端調試

最後

為了統一的操作體驗,對於一些不支持websocket的瀏覽器,請使用socketjs技術做客户端開發。