Javascript 为什么WebSocket比AJAX$.post()慢?
我一直在本地测试Javascript 为什么WebSocket比AJAX$.post()慢?,javascript,java,jquery,ajax,websocket,Javascript,Java,Jquery,Ajax,Websocket,我一直在本地测试WebSockets和$.post()之间的差异,发现在以下情况下,$.post()始终比WebSockets快76%: 场景 客户端向服务器发送命令(“启动”) 服务器用命令(“就绪”)进行响应 客户端向服务器发布命令(“文件”) 服务器以1.4MB(约)文本文件的内容响应,该文本文件包含单词“Lorem” 客户端收到此文件并重复该循环10次 客户端AJAX$.post(): 服务器后控制器: @WebServlet("/post") public class PostCont
WebSockets
和$.post()
之间的差异,发现在以下情况下,$.post()始终比WebSockets快76%:
场景
AJAX
$.post():
服务器后控制器:
@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();
}
}
}
}
@ServerEndpoint(value=“/server”)
公共类服务器{
私有静态ArrayList sessionList=新ArrayList();
@一个错误
公共作废申报人(会话,可丢弃的t){
sessionList.remove(会话);
}
@奥诺彭
公共开放(会议){
试一试{
sessionList.add(会话);
session.getBasicRemote().sendText(“就绪”);
}捕获(IOE异常){
}
}
@一次
公共void onClose(会话){
sessionList.remove(会话);
}
@OnMessage
公共void onMessage(字符串msg)抛出JSONException{
字符串输出=”;
if(msg.equals(“文件”)){
试一试{
URL resource=getClass().getResource(“/”);
字符串路径=resource.getPath();
字符串absoluteDiskPath=path+“../../resources/file.txt”;
output=FileUtils.readFileToString(新文件(绝对磁盘路径));
}捕获(IOE异常){
e、 printStackTrace();
}
}
如果(消息等于(“Lorem”)){
输出=“已接收”;
}
如果(消息等于(“开始”)){
输出=“就绪”;
}
for(inti=0,size=sessionList.size();i
此测试是使用JQuery的$.post()和JavaScripts Websocket API在本地完成的。服务器是用Java编写的
在上一次测试中,AJAX$.post()方法在0.450秒内完成了10个调用,而10个Websocket API调用在1.877秒内完成
我本来希望10个websocket调用能够以最快的速度完成,因为每个消息发送的标题数量较少
那么,为什么JQuery的$.post()比WebSocket快呢
我最初的预感是,帖子(默认情况下是异步的)都是并行进行的,对websocket调用的调用是同步进行的。您是否与Fiddler/Firebug等进行了检查,以查看是否有9个WebSocket打开?取舍是,如果打开一个websocket并将其视为一个管道,则应该更快,但如果打开多个websocket,则效率较低。当执行更多调用和请求时,性能差异会减小吗?如果我理解正确,WebSocket握手会增加初始延迟,但一旦建立通信,数据传输比使用Ajax更快,因为WebSocket不会共享Ajax的HTTP头开销。@GordonMacDonald是的,我只使用一个WebSocket连接。虽然默认情况下AJAX POST是异步的,但它们是以顺序方式调用的,
httpPost()
方法根据从服务器接收到的数据递归调用自己。每次都要创建一个新连接。HTTP不会这样做(至少在保持活动状态时不会)。更好的比较是创建一个套接字并使用它发送9条消息。@Paulpro在httpPost()完成9次自身调用后(总共10次调用)。然后打开单个websocket连接,并在单个websocket连接上发出10个文件请求。
@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();
}
}
}
}