长轮询的使用实现_长轮询和短轮询

长轮询的使用实现_长轮询和短轮询轮询(Polling):是指不管服务器端有没有更新,客户端(通常是指浏览器)都定时的发送请求进行查询,轮询的结果可能是服务器端有新的更新过来,也可能什么也没有,只是返回个空的信息。不管结果如何,客户端处理完后到下一个定时时间点将继续下一轮的轮询。长轮询(LongPolling):长轮询的服务其客户端是不做轮询的,客户端在发起一次请求后立即挂起,一直到服务器端有更新的时候,服务器才会主动推送信息到…

大家好,又见面了,我是你们的朋友全栈君。如果您正在找激活码,请点击查看最新教程,关注关注公众号 “全栈程序员社区” 获取激活教程,可能之前旧版本教程已经失效.最新Idea2022.1教程亲测有效,一键激活。

Jetbrains全家桶1年46,售后保障稳定

轮询(Polling):是指不管服务器端有没有更新,客户端(通常是指浏览器)都定时的发送请求进行查询,轮询的结果可能是服务器端有新的更新过来,也可能什么也没有,只是返回个空的信息。不管结果如何,客户端处理完后到下一个定时时间点将继续下一轮的轮询。

长轮询(Long Polling):长轮询的服务其客户端是不做轮询的,客户端在发起一次请求后立即挂起,一直到服务器端有更新的时候,服务器才会主动推送信息到客户端。 在服务器端有更新并推送信息过来之前这个周期内,客户端不会有新的多余的请求发生,服务器端对此客户端也啥都不用干,只保留最基本的连接信息,一旦服务器有更新将推送给客户端,客户端将相应的做出处理,处理完后再重新发起下一轮请求。

可见,长轮询的特点:

服务器端会阻塞请求直到有数据传递或超时才返回.

客户端响应处理函数会在处理完服务器返回的信息后,再次发出请求,重新建立连接.

当客户端处理接收的数据、重新建立连接时,服务器端可能有新的数据到达;这些信息会被服务器端保存直到客户端重新建立连接,客户端会一次把当前服务器端所有的信息取回。

Java-长轮询(Long polling)实现

服务端

package _20200418.example;

import com.sun.net.httpserver.HttpServer;

import java.io.IOException;

import java.io.OutputStream;

import java.net.InetSocketAddress;

import java.nio.charset.StandardCharsets;

import java.util.Random;

import java.util.concurrent.Executors;

import java.util.concurrent.TimeUnit;

import java.util.concurrent.atomic.AtomicLong;

/**

* 长轮询服务端

*

* Created by zfh on 2020/04/18

*/

public class server {

private final AtomicLong value = new AtomicLong();

private void start() throws IOException {

HttpServer httpServer = HttpServer.create(new InetSocketAddress(8080), 0);

httpServer.setExecutor(Executors.newCachedThreadPool());

httpServer.createContext(“/long-polling”, httpExchange -> {

byte[] data = fetchData();

httpExchange.sendResponseHeaders(200, data.length);

OutputStream outputStream = httpExchange.getResponseBody();

outputStream.write(data);

outputStream.close();

httpExchange.close();

});

httpServer.start();

}

private byte[] fetchData() {

try {

// 由于客户端设置的超时时间是50s,

// 为了更好的展示长轮询,这边random 100,模拟服务端hold住大于50和小于50的情况。

Random random = new Random();

TimeUnit.SECONDS.sleep(random.nextInt(100));

} catch (InterruptedException ignored) {

}

return Long.toString(value.getAndIncrement()).getBytes(StandardCharsets.UTF_8);

}

public static void main(String[] args) throws IOException {

server server = new server();

server.start();

}

}

客户端

package _20200418.example;

import java.io.BufferedReader;

import java.io.IOException;

import java.io.InputStreamReader;

import java.net.HttpURLConnection;

import java.net.URL;

import java.nio.charset.StandardCharsets;

import java.util.concurrent.atomic.AtomicLong;

/**

* 长轮询-客户端

*

* Created by zfh on 2020/04/18

*/

public class client {

private static final String SYNC_URL = “http://localhost:8080/long-polling”;

private final AtomicLong sequence = new AtomicLong();

void poll() {

// 循环执行,保证每次longpolling结束,再次发起longpolling

// 结束条件,超时或者拿到数据

while (!Thread.interrupted()) {

doPoll();

}

}

private void doPoll() {

System.out.println(“第” + (sequence.incrementAndGet()) + “次 longpolling”);

long startMillis = System.currentTimeMillis();

HttpURLConnection connection = null;

try {

URL getUrl = new URL(SYNC_URL);

connection = (HttpURLConnection) getUrl.openConnection();

// 50s作为长轮询超时时间

connection.setReadTimeout(50000);

connection.setConnectTimeout(3000);

connection.setRequestMethod(“GET”);

connection.setUseCaches(false);

connection.setDoOutput(true);

connection.setDoInput(true);

connection.setRequestProperty(“Content-Type”, “application/json;charset=UTF-8”);

connection.setRequestProperty(“Accept-Charset”, “application/json;charset=UTF-8”);

connection.connect();

if (200 == connection.getResponseCode()) {

BufferedReader reader = null;

try {

reader = new BufferedReader(new InputStreamReader(connection.getInputStream(), StandardCharsets.UTF_8));

StringBuilder result = new StringBuilder(256);

String line;

while ((line = reader.readLine()) != null) {

result.append(line);

}

System.out.println(“结果 ” + result);

} finally {

if (reader != null) {

reader.close();

}

}

}

} catch (IOException e) {

System.out.println(“request failed”);

} finally {

long elapsed = (System.currentTimeMillis() – startMillis) / 1000;

System.out.println(“connection close” + ” ” + “elapse ” + elapsed + “s”);

if (connection != null) {

connection.disconnect();

}

System.out.println();

}

}

public static void main(String[] args) throws InterruptedException {

client bootstrap = new client();

bootstrap.poll();

Thread.sleep(Integer.MAX_VALUE);

}

}

版权声明:本文内容由互联网用户自发贡献,该文观点仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请联系我们举报,一经查实,本站将立刻删除。

发布者:全栈程序员-站长,转载请注明出处:https://javaforall.net/230792.html原文链接:https://javaforall.net

(0)
全栈程序员-站长的头像全栈程序员-站长


相关推荐

  • pyquery安装

    pyquery安装pyquery是一个类似jquery的工具,不过它是在服务端进行处理的,不像jquery是在浏览器中进行处理。如果我们要进行网络爬虫,爬取有用的信息,那么它是我至今见到的不二选择。我们当然可以自己爬取网页,然后可以通过正则表达式,选取有用的信息,但这其实要求挺高的。我以前也做过爬虫工具,专门抓取招聘网站的招聘信息,但我发先我以前做的实在是复杂。而我们程序员很重要的一点是,不要重复的发明轮子,我们只

    2022年6月6日
    102
  • python读取指定内存_更改python保存路径

    python读取指定内存_更改python保存路径importosimportsysfromctypesimport*windll.kernel32.WriteProcessMemory.argtypes=[c_void_p,c_void_p,c_void_p,c_int,c_void_p]windll.kernel32.WriteProcessMemory.restype=c_void…

    2025年9月5日
    7
  • matlab plot函数详解取值范围_matlab为什么plot不出来图

    matlab plot函数详解取值范围_matlab为什么plot不出来图 在matlab中,plot函数用来绘制二维图像。1.plot默认格式 plot(x,y)这种格式中,若x,y是向量,则它们必须具有相同的长度。函数将以x为横轴,绘制y。                  若x,y都是矩阵,则它们必须具有相同的尺寸,plot函数将针对x的各列绘制y的每列。更确切的说,将x和y的对应的各列取出来,绘制曲线。比如x和y分别为n*n…

    2022年10月16日
    4
  • Web聊天工具

    Web聊天工具8款开源聊天系统和程序,包含聊天程序,或是搭建你自己的聊天室系统。来源于:http://parandroid.com/8-open-source-chat/ MOHAChat http://mohachat.org/MOHAChat是一个客户端采用Ajax技术,服务端基于PHP与MySQL的点对点聊天系统。类似于GTalk。 phpFreeChat http://www.p

    2022年6月15日
    62
  • 如何在matlab中画二元函数的图像,Matlab画怎么画这个二元函数图像「建议收藏」

    如何在matlab中画二元函数的图像,Matlab画怎么画这个二元函数图像「建议收藏」www.mh456.com防采集。二元函数可以用mesh或者surf函数画图。1、首先打开matlab。2、在matlab当前目录空间右键。3、然后点击new->M-File。4、然后将文件命令为hello.m。5、然后双击该文件,输入[Rmdm]=meshgrid(15:5:50,1:10);6、然后添加f=0.034488*(Rm.^1.9400).*(10^-0….

    2025年9月30日
    2
  • Spring全家桶之SpringSession「建议收藏」

    Spring全家桶之SpringSession「建议收藏」SpringSession和SpringSessionMongoDB相关的实用知识的整理,希望能够帮助更多人~~~

    2022年10月16日
    3

发表回复

您的邮箱地址不会被公开。 必填项已用 * 标注

关注全栈程序员社区公众号