我一直在本地测试WebSockets
和$.post()
之间的区别,并且发现$ .post()在以下情况下比WebSockets一样强<76> :
方案
客户端向服务器发布命令(&#34; start&#34;)。
服务器以命令响应(&#34;准备就绪&#34;)。
客户将命令(&#34;文件&#34;)发布到服务器。
服务器响应包含单词&#34; Lorem&#34;的1.4MB(大约)文本文件的内容。
客户端收到此文件并重复循环10次。
客户AJAX
$ .post():
httpPost('start', 0);
function httpPost(cmd, iteration) {
$.post('http://path/to/server', {cmd:cmd}, function(data){
switch(data) {
case "ready":
// request file
httpPost('file', iteration);
break;
case "received":
if(iteration == 9) {
// total time taken is recorded here (omitted)
}else{
httpPost('start', ++iteration);
break;
}
}
if(data.indexOf('Lorem') > -1) {
// acknowledge receipt of file
httpPost('Lorem', iteration);
}
});
}
Server PostController:
@WebServlet("/post")
public class PostController extends HttpServlet{
private static final long serialVersionUID = 1L;
@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
String cmd = req.getParameter("cmd");
PrintWriter out = resp.getWriter();
if(cmd != null) {
switch(cmd) {
case "start":
out.append("ready");
break;
case "file":
String absoluteDiskPath = getServletContext().getRealPath("/resources/file.txt");
String contents = FileUtils.readFileToString(new File(absoluteDiskPath));
out.append(contents);
break;
case "concurrency":
out.append("concurrency");
break;
case "Lorem":
out.append("received");
break;
}
}
out.close();
}
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
super.doGet(req, resp);
}
}
客户WebSockets API
:
startWebSocket(); // open a single websocket connection and request a file 10 times
function startWebSocket() {
var url = "ws://path/to/server";
var socket = new WebSocket(url);
var iteration = 0;
socket.onmessage = function (event) {
if (event.data.indexOf('ready') > -1) {
// request file
socket.send('file');
}
if(event.data.indexOf('Lorem') > -1) {
// acknowledge receipt of file
socket.send('Lorem');
}
if(event.data.indexOf('received') > -1) {
if(iteration == 9) {
// total time taken is recorded here (omitted)
}else{
socket.send('start');
iteration++;
}
}
}
socket.onopen = function (event) {
};
socket.onclose = function (event) {
};
socket.onerror = function (event) {
};
}
服务器ServerEndPoint
:
@ServerEndpoint(value = "/server")
public class Server{
private static ArrayList<Session> sessionList = new ArrayList<Session>();
@OnError
public void onError(Session session, Throwable t) {
sessionList.remove(session);
}
@OnOpen
public void onOpen(Session session) {
try {
sessionList.add(session);
session.getBasicRemote().sendText("ready");
} catch (IOException e) {
}
}
@OnClose
public void onClose(Session session) {
sessionList.remove(session);
}
@OnMessage
public void onMessage(String msg) throws JSONException {
String output = "";
if(msg.equals("file")) {
try {
URL resource = getClass().getResource("/");
String path = resource.getPath();
String absoluteDiskPath = path + "../../resources/file.txt";
output = FileUtils.readFileToString(new File(absoluteDiskPath));
} catch (IOException e) {
e.printStackTrace();
}
}
if(msg.equals("Lorem")) {
output = "received";
}
if(msg.equals("start")) {
output = "ready";
}
for (int i = 0, size = sessionList.size(); i < size; i++) {
try {
sessionList.get(i).getBasicRemote().sendText(output);
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
使用JQuery的$ .post()和JavaScripts Websocket API在本地完成此测试。服务器是用Java编写的。
在最后一次测试中,AJAX $ .post()方法在 0.450 秒内完成了10次调用,而10次Websocket API调用在 1.877 秒内完成。
我原本希望10个websocket调用能够以最快的速度完成,因为每条消息都会发送较少的标题。
那么,为什么JQuery的$ .post()比WebSockets更快?