cs java 消息推送_java版Web Socket,实现消息推送

# web socket是什么?

WebSocket协议是基于TCP的一种新的网络协议。

它实现了浏览器与服务器全双工(full-duplex)通信,允许服务器主动发送信息给客户端。

## 用途

实时Web应用的解决方案,实现Web的实时通信。

说的再直白点,html的消息推送。

假如你有一个页面,数据不定期更改,通常的做法就是轮询,客户端不停地向服务器请求最新的数据。

当有了web socket,数据变动时 让服务器通知客户端,启不是很美妙?

## 请求示例

(1) 默认端口是80和443(ssl)。

(2) 协议标识符是ws和ws(ssl)。

(3) 请求报文示例

ba819ff29beeb9a4aaa4f6d133cc5425.png

efec1fd5bddc0b6b8522b99da3c7bd0f.png

General--------------------------------------------Request URL:ws://localhost:8080/j2ee-websocket/websocket/1Request Method:GET

Status Code:101Switching Protocols---------------------------------------------Response Headers---------------------------------------------Connection:upgrade

Date:Tue,05 Dec 2017 01:22:45GMT

Sec-WebSocket-Accept:cRxT/XcOpnsleDb1KdydWXOw+us=Sec-WebSocket-Extensions:permessage-deflate;client_max_window_bits=15Server:Apache-Coyote/1.1Upgrade:websocket

web socket request

# 代码实现

代码分为3个部分:javax.websocket api实现,使用观察者模式增强,google/jquery-websocket代码库。

## 服务端 java代码

jar -- 引入javax.websocket,或引入javaee-api。

这里只展示api接口特性。

/***Web Socket api implement

*参数以URL路径参数传递*/@ServerEndpoint(value= "/websocket/{principal}")public classDefaultWebSocket {/**Web Socket连接建立成功的回调方法*/@OnOpenpublic void onOpen(@PathParam("principal") String principal, Session session) {

//...

}/**服务端收到客户端发来的消息*/@OnMessagepublic void onMessage(@PathParam("principal") String principal, String message, Session session) {

//...

}

@OnClosepublic void onClose(@PathParam("principal") String principal, Session session) {

//...

}

@OnErrorpublic void onError(@PathParam("principal") String principal, Session session, Throwable error) {

//...

}

}

## 服务端推送消息至客户端 java代码

这里使用了 观察者模式,对websocket进行了增强,详见完整代码:github:j2ee-websocket。

/**服务端向客户端推送消息*/

public voidnotifyTest() {

String principal= "1";

String type= "radio";

JSONObject data= newJSONObject();

data.put("title", "test web socket");

data.put("content", "Have you recieve this msg?--this msg from server.");

WebSocketSubject subject=WebSocketSubject.Holder.getSubject(principal);

subject.notify(type, data.toJSONString());

}

## 客户端 javascript代码

普通js代码

ba819ff29beeb9a4aaa4f6d133cc5425.png

efec1fd5bddc0b6b8522b99da3c7bd0f.png

var websocket = null;var principal = '1';var socketURL = 'ws://' +window.location.host+ '/j2ee-websocket/websocket/' +principal;//判断当前浏览器是否支持WebSocket

if('WebSocket' inwindow){

websocket= newWebSocket(socketURL);

}else{

alert('Not support websocket');

}//连接发生错误的回调方法

websocket.onerror = function(event){

alert("error");

};//连接成功建立的回调方法

websocket.onopen = function(){

alert("open");

}//接收到消息的回调方法

websocket.onmessage = function(event){

alert('recive : ' +event.data);

}//连接关闭的回调方法

websocket.onclose = function(event){

alert("close");

}//发送消息

functionsend(message){

websocket.send(message);

}

web socket js

推荐:google/jquery-websocket代码 (http://code.google.com/p/jquery-websocket)

google/jquery-websocket增加了消息的类型,将消息拆分为{"type":"","message":""}。

这样更灵活,可以根据业务类型,定义type,如:通知,公告,广播,发文等...

var principal = '1';var socketURL = 'ws://' +window.location.host+ '/j2ee-websocket/websocket/' +principal;

websocket=$.websocket(socketURL, {

open :function() {//when the socket opens

alert("open");

},

close :function() {//when the socket closes

alert("close");

},//收到服务端推送的消息处理

events : {'radio' : function(event) {

console.info($.parseJSON(event.data));

},'notice' : function(event) {

console.info($.parseJSON(event.data));

},//... more custom type of message

}

});//发送消息

functionsend() {

websocket.send('radio', " hello,this msg from client request");

}

# 客户端运行示例

c28918ac4bacdefad070fcae37b33517.png

--END--

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值