设为首页 收藏本站
查看: 605|回复: 0

[经验分享] WebSocket +Jetty+jQuery 实现服务器消息推送例子

[复制链接]

尚未签到

发表于 2017-2-27 10:05:17 | 显示全部楼层 |阅读模式
  服务器servlet代码

package flowersinthesand.example;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.LinkedHashMap;
import java.util.Map;
import java.util.Queue;
import java.util.UUID;
import java.util.concurrent.BlockingQueue;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ConcurrentLinkedQueue;
import java.util.concurrent.LinkedBlockingQueue;
import javax.servlet.AsyncContext;
import javax.servlet.AsyncEvent;
import javax.servlet.AsyncListener;
import javax.servlet.ServletConfig;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.eclipse.jetty.util.UrlEncoded;
import org.eclipse.jetty.websocket.WebSocket;
import org.eclipse.jetty.websocket.WebSocketServlet;
import com.google.gson.Gson;
@WebServlet(urlPatterns = "/chat", asyncSupported = true)
public class ChatServlet extends WebSocketServlet {
private static final long serialVersionUID = 4805728426990609124L;
private Map<String, AsyncContext> asyncContexts = new ConcurrentHashMap<String, AsyncContext>();
private Queue<ChatWebSocket> webSockets = new ConcurrentLinkedQueue<ChatWebSocket>();
private BlockingQueue<String> messages = new LinkedBlockingQueue<String>();
private Thread notifier = new Thread(new Runnable() {
public void run() {
while (true) {
try {
// Waits until a message arrives
String message = messages.take();
// Sends the message to all the AsyncContext's response
for (AsyncContext asyncContext : asyncContexts.values()) {
try {
sendMessage(asyncContext.getResponse().getWriter(), message);
} catch (Exception e) {
asyncContexts.values().remove(asyncContext);
}
}
// Sends the message to all the WebSocket's connection
for (ChatWebSocket webSocket : webSockets) {
try {
webSocket.connection.sendMessage(message);
} catch (Exception e) {
webSockets.remove(webSocket);
}
}
} catch (InterruptedException e) {
break;
}
}
}
});
private void sendMessage(PrintWriter writer, String message) throws IOException {
// default message format is message-size ; message-data ;
writer.print(message.length());
writer.print(";");
writer.print(message);
writer.print(";");
writer.flush();
}
@Override
public void init(ServletConfig config) throws ServletException {
super.init(config);
notifier.start();
}
// GET method is used to establish a stream connection
@Override
protected void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
// Content-Type header
response.setContentType("text/plain");
response.setCharacterEncoding("utf-8");
// Access-Control-Allow-Origin header
response.setHeader("Access-Control-Allow-Origin", "*");
PrintWriter writer = response.getWriter();
// Id
final String id = UUID.randomUUID().toString();
writer.print(id);
writer.print(';');
// Padding
for (int i = 0; i < 1024; i++) {
writer.print(' ');
}
writer.print(';');
writer.flush();
final AsyncContext ac = request.startAsync();
ac.addListener(new AsyncListener() {
public void onComplete(AsyncEvent event) throws IOException {
asyncContexts.remove(id);
}
public void onTimeout(AsyncEvent event) throws IOException {
asyncContexts.remove(id);
}
public void onError(AsyncEvent event) throws IOException {
asyncContexts.remove(id);
}
public void onStartAsync(AsyncEvent event) throws IOException {
}
});
asyncContexts.put(id, ac);
}
// POST method is used to communicate with the server
@Override
protected void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
request.setCharacterEncoding("utf-8");
AsyncContext ac = asyncContexts.get(request.getParameter("metadata.id"));
if (ac == null) {
return;
}
// close-request
if ("close".equals(request.getParameter("metadata.type"))) {
ac.complete();
return;
}
// send-request
Map<String, String> data = new LinkedHashMap<String, String>();
data.put("username", request.getParameter("username"));
data.put("message", request.getParameter("message"));
try {
messages.put(new Gson().toJson(data));
} catch (InterruptedException e) {
throw new IOException(e);
}
}
@Override
public WebSocket doWebSocketConnect(HttpServletRequest request, String protocol) {
return new ChatWebSocket();
}
class ChatWebSocket implements WebSocket.OnTextMessage {
Connection connection;
@Override
public void onOpen(Connection connection) {
this.connection = connection;
webSockets.add(this);
}
@Override
public void onClose(int closeCode, String message) {
webSockets.remove(this);
}
@Override
public void onMessage(String queryString) {
// Parses query string
UrlEncoded parameters = new UrlEncoded(queryString);
Map<String, String> data = new LinkedHashMap<String, String>();
data.put("username", parameters.getString("username"));
data.put("message", parameters.getString("message"));
try {
messages.put(new Gson().toJson(data));
} catch (InterruptedException e) {
throw new RuntimeException(e);
}
}
}
@Override
public void destroy() {
messages.clear();
webSockets.clear();
asyncContexts.clear();
notifier.interrupt();
}
}

  html代码

<!DOCTYPE html>
<html>
<head>
<title>Chat - Jetty 8</title>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<script type="text/javascript" src="jquery-1.5.0.js"></script>
<script type="text/javascript" src="jquery.stream-1.2.js"></script>
<script type="text/javascript">
$.stream.setup({enableXDR: true});
var chat = {
lastUsername: "Donghwan Kim",
username: $.trim(window.prompt("Username?")) || "Anonymous" + $(window).width()
};
$(function() {
$.stream("chat", {
dataType: "json",
context: $("#content")[0],
open: function(event, stream) {
$("#editor .message").removeAttr("disabled").focus();
stream.send({username: chat.username, message: "Hello"});
},
message: function(event) {
if (chat.lastUsername !== event.data.username) {
$("<p />").addClass("user").text(chat.lastUsername = event.data.username).appendTo(this);
}
$("<p />").addClass("message").text(event.data.message).appendTo(this);
this.scrollTop = this.scrollHeight;
},
error: function() {
$("#editor .message").attr("disabled", "disabled");
},
close: function() {
$("#editor .message").attr("disabled", "disabled");
}
});
$("#editor .user").text(chat.username);
$("#editor .message").keyup(function(event) {
if (event.which === 13 && $.trim(this.value)) {
$.stream().send({username: chat.username, message: this.value});
this.value = "";
}
});
$(window).resize(function() {
var content = $("#content").height($(window).height() - $("#editor").outerHeight(true) - 15)[0];
content.scrollTop = content.scrollHeight;
}).resize();
});
</script>
<style>
body {padding: 0; margin: 0; min-width: 320px; font-family: 'Trebuchet MS','Malgun Gothic',Verdana,Helvetica,Arial,sans-serif; font-size: 62.5%; color: #333333}
.content {height: 100%; overflow-y: auto; padding: 14px 15px 0 25px;}
.content p {margin: 0; padding: 0;}
.content .user {font-size: 1.8em; color: #3e3e3e; font-weight: bold; letter-spacing: -1px; margin-top: 0.5em;}
.content .message {font-size: 1.3em; color: #444444; line-height: 1.7em; word-wrap: break-word;}
.editor {margin: 0 25px 15px 25px;}
.editor .user {font-size: 1.5em; display: inline-block; margin: 1em;}
.editor input {font-family: 'Trebuchet MS','Malgun Gothic',Verdana,Helvetica,Arial,sans-serif;}
.editor .message {width: 100%; height: 28px; line-height: 28px; border: medium none; border-color: #E5E5E5 #DBDBDB #D2D2D2; border-style: solid; border-width: 1px;}
</style>
</head>
<body>
<div id="content" class="content">
<p class="user"><span>Donghwan Kim</span></p>
<p class="message">Welcome to jQuery Stream!</p>
</div>
<div id="editor" class="editor">
<p class="user"></p>
<form action="#" >
<input class="message" type="text" disabled="disabled" />
</form>
</div>
</body>
</html>

  另需要
  jquery-1.5.0.js
  jquery.stream-1.2.js
  参考 https://code.google.com/p/jquery-stream/

 
  压力测试插件
  https://github.com/kawasima/jmeter-websocket

运维网声明 1、欢迎大家加入本站运维交流群:群②:261659950 群⑤:202807635 群⑦870801961 群⑧679858003
2、本站所有主题由该帖子作者发表,该帖子作者与运维网享有帖子相关版权
3、所有作品的著作权均归原作者享有,请您和我们一样尊重他人的著作权等合法权益。如果您对作品感到满意,请购买正版
4、禁止制作、复制、发布和传播具有反动、淫秽、色情、暴力、凶杀等内容的信息,一经发现立即删除。若您因此触犯法律,一切后果自负,我们对此不承担任何责任
5、所有资源均系网友上传或者通过网络收集,我们仅提供一个展示、介绍、观摩学习的平台,我们不对其内容的准确性、可靠性、正当性、安全性、合法性等负责,亦不承担任何法律责任
6、所有作品仅供您个人学习、研究或欣赏,不得用于商业或者其他用途,否则,一切后果均由您自己承担,我们对此不承担任何法律责任
7、如涉及侵犯版权等问题,请您及时通知我们,我们将立即采取措施予以解决
8、联系人Email:admin@iyunv.com 网址:www.yunweiku.com

所有资源均系网友上传或者通过网络收集,我们仅提供一个展示、介绍、观摩学习的平台,我们不对其承担任何法律责任,如涉及侵犯版权等问题,请您及时通知我们,我们将立即处理,联系人Email:kefu@iyunv.com,QQ:1061981298 本贴地址:https://www.iyunv.com/thread-347787-1-1.html 上篇帖子: cometd Dojo jetty整合的一个小例子 下篇帖子: 目前发现的最好最快的直接在ECLIPSE中JETTY调试方式
您需要登录后才可以回帖 登录 | 立即注册

本版积分规则

扫码加入运维网微信交流群X

扫码加入运维网微信交流群

扫描二维码加入运维网微信交流群,最新一手资源尽在官方微信交流群!快快加入我们吧...

扫描微信二维码查看详情

客服E-mail:kefu@iyunv.com 客服QQ:1061981298


QQ群⑦:运维网交流群⑦ QQ群⑧:运维网交流群⑧ k8s群:运维网kubernetes交流群


提醒:禁止发布任何违反国家法律、法规的言论与图片等内容;本站内容均来自个人观点与网络等信息,非本站认同之观点.


本站大部分资源是网友从网上搜集分享而来,其版权均归原作者及其网站所有,我们尊重他人的合法权益,如有内容侵犯您的合法权益,请及时与我们联系进行核实删除!



合作伙伴: 青云cloud

快速回复 返回顶部 返回列表