java 长链接 实现方式_[Java基础]-- 实现长链接的client端请求

该博客展示了如何使用Apache HttpClient库在Java中实现HTTP长连接的客户端请求。通过创建HttpProcessor、HttpRequestExecutor,以及处理多个POST请求,演示了在不同HTTP实体类型下保持连接的步骤。
摘要由CSDN通过智能技术生成

1、版本:httpclient-4.5.2   httpcore-4.4.5

2、pom.xml文件

org.apache.httpcomponents

httpclient

4.5.2

org.apache.httpcomponents

httpcore

4.4.5

3、POST长链接的实现代码:

/*

* ====================================================================

* Licensed to the Apache Software Foundation (ASF) under one

* or more contributor license agreements. See the NOTICE file

* distributed with this work for additional information

* regarding copyright ownership. The ASF licenses this file

* to you under the Apache License, Version 2.0 (the

* "License"); you may not use this file except in compliance

* with the License. You may obtain a copy of the License at

*

* http://www.apache.org/licenses/LICENSE-2.0

*

* Unless required by applicable law or agreed to in writing,

* software distributed under the License is distributed on an

* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY

* KIND, either express or implied. See the License for the

* specific language governing permissions and limitations

* under the License.

* ====================================================================

*

* This software consists of voluntary contributions made by many

* individuals on behalf of the Apache Software Foundation. For more

* information on the Apache Software Foundation, please see

* .

*

*/

package org.apache.http.examples;

import java.io.ByteArrayInputStream;

import java.net.Socket;

import org.apache.http.ConnectionReuseStrategy;

import org.apache.http.Consts;

import org.apache.http.HttpEntity;

import org.apache.http.HttpHost;

import org.apache.http.HttpResponse;

import org.apache.http.entity.ByteArrayEntity;

import org.apache.http.entity.ContentType;

import org.apache.http.entity.InputStreamEntity;

import org.apache.http.entity.StringEntity;

import org.apache.http.impl.DefaultBHttpClientConnection;

import org.apache.http.impl.DefaultConnectionReuseStrategy;

import org.apache.http.message.BasicHttpEntityEnclosingRequest;

import org.apache.http.protocol.HttpCoreContext;

import org.apache.http.protocol.HttpProcessor;

import org.apache.http.protocol.HttpProcessorBuilder;

import org.apache.http.protocol.HttpRequestExecutor;

import org.apache.http.protocol.RequestConnControl;

import org.apache.http.protocol.RequestContent;

import org.apache.http.protocol.RequestExpectContinue;

import org.apache.http.protocol.RequestTargetHost;

import org.apache.http.protocol.RequestUserAgent;

import org.apache.http.util.EntityUtils;

/**

* Elemental example for executing multiple POST requests sequentially.

*/

public class ElementalHttpPost {

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

HttpProcessor httpproc = HttpProcessorBuilder.create()

.add(new RequestContent())

.add(new RequestTargetHost())

.add(new RequestConnControl())

.add(new RequestUserAgent("Test/1.1"))

.add(new RequestExpectContinue(true)).build();

HttpRequestExecutor httpexecutor = new HttpRequestExecutor();

HttpCoreContext coreContext = HttpCoreContext.create();

HttpHost host = new HttpHost("localhost", 8080);

coreContext.setTargetHost(host);

DefaultBHttpClientConnection conn = new DefaultBHttpClientConnection(8 * 1024);

ConnectionReuseStrategy connStrategy = DefaultConnectionReuseStrategy.INSTANCE;

try {

HttpEntity[] requestBodies = {

new StringEntity(

"This is the first test request",

ContentType.create("text/plain", Consts.UTF_8)),

new ByteArrayEntity(

"This is the second test request".getBytes(Consts.UTF_8),

ContentType.APPLICATION_OCTET_STREAM),

new InputStreamEntity(

new ByteArrayInputStream(

"This is the third test request (will be chunked)"

.getBytes(Consts.UTF_8)),

ContentType.APPLICATION_OCTET_STREAM)

};

for (int i = 0; i < requestBodies.length; i++) {

if (!conn.isOpen()) {

Socket socket = new Socket(host.getHostName(), host.getPort());

conn.bind(socket);

}

BasicHttpEntityEnclosingRequest request = new BasicHttpEntityEnclosingRequest("POST",

"/servlets-examples/servlet/RequestInfoExample");

request.setEntity(requestBodies[i]);

System.out.println(">> Request URI: " + request.getRequestLine().getUri());

httpexecutor.preProcess(request, httpproc, coreContext);

HttpResponse response = httpexecutor.execute(request, conn, coreContext);

httpexecutor.postProcess(response, httpproc, coreContext);

System.out.println("<< Response: " + response.getStatusLine());

System.out.println(EntityUtils.toString(response.getEntity()));

System.out.println("==============");

if (!connStrategy.keepAlive(response, coreContext)) {

conn.close();

} else {

System.out.println("Connection kept alive...");

}

}

} finally {

conn.close();

}

}

}

package org.apache.http.examples;

import java.io.ByteArrayInputStream;

import java.net.Socket;

import org.apache.http.ConnectionReuseStrategy;

import org.apache.http.Consts;

import org.apache.http.HttpEntity;

import org.apache.http.HttpHost;

import org.apache.http.HttpResponse;

import org.apache.http.entity.ByteArrayEntity;

import org.apache.http.entity.ContentType;

import org.apache.http.entity.InputStreamEntity;

import org.apache.http.entity.StringEntity;

import org.apache.http.impl.DefaultBHttpClientConnection;

import org.apache.http.impl.DefaultConnectionReuseStrategy;

import org.apache.http.message.BasicHttpEntityEnclosingRequest;

import org.apache.http.protocol.HttpCoreContext;

import org.apache.http.protocol.HttpProcessor;

import org.apache.http.protocol.HttpProcessorBuilder;

import org.apache.http.protocol.HttpRequestExecutor;

import org.apache.http.protocol.RequestConnControl;

import org.apache.http.protocol.RequestContent;

import org.apache.http.protocol.RequestExpectContinue;

import org.apache.http.protocol.RequestTargetHost;

import org.apache.http.protocol.RequestUserAgent;

import org.apache.http.util.EntityUtils;

/**

* Elemental example for executing multiple POST requests sequentially.

*/

public class ElementalHttpPost {

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

HttpProcessor httpproc = HttpProcessorBuilder.create()

.add(new RequestContent())

.add(new RequestTargetHost())

.add(new RequestConnControl())

.add(new RequestUserAgent("Test/1.1"))

.add(new RequestExpectContinue(true)).build();

HttpRequestExecutor httpexecutor = new HttpRequestExecutor();

HttpCoreContext coreContext = HttpCoreContext.create();

HttpHost host = new HttpHost("localhost", 8080);

coreContext.setTargetHost(host);

DefaultBHttpClientConnection conn = new DefaultBHttpClientConnection(8 * 1024);

ConnectionReuseStrategy connStrategy = DefaultConnectionReuseStrategy.INSTANCE;

try {

HttpEntity[] requestBodies = {

new StringEntity(

"This is the first test request",

ContentType.create("text/plain", Consts.UTF_8)),

new ByteArrayEntity(

"This is the second test request".getBytes(Consts.UTF_8),

ContentType.APPLICATION_OCTET_STREAM),

new InputStreamEntity(

new ByteArrayInputStream(

"This is the third test request (will be chunked)"

.getBytes(Consts.UTF_8)),

ContentType.APPLICATION_OCTET_STREAM)

};

for (int i = 0; i < requestBodies.length; i++) {

if (!conn.isOpen()) {

Socket socket = new Socket(host.getHostName(), host.getPort());

conn.bind(socket);

}

BasicHttpEntityEnclosingRequest request = new BasicHttpEntityEnclosingRequest("POST",

"/servlets-examples/servlet/RequestInfoExample");

request.setEntity(requestBodies[i]);

System.out.println(">> Request URI: " + request.getRequestLine().getUri());

httpexecutor.preProcess(request, httpproc, coreContext);

HttpResponse response = httpexecutor.execute(request, conn, coreContext);

httpexecutor.postProcess(response, httpproc, coreContext);

System.out.println("<< Response: " + response.getStatusLine());

System.out.println(EntityUtils.toString(response.getEntity()));

System.out.println("==============");

if (!connStrategy.keepAlive(response, coreContext)) {

conn.close();

} else {

System.out.println("Connection kept alive...");

}

}

} finally {

conn.close();

}

}

}

4、官方参考:http://hc.apache.org/httpcomponents-core-ga/httpcore/

好的,我了解了。针对你的问题,我可以为你提供一些基于Java Socket的多客户Client-Server聊天程序的实现步骤。 步骤如下: 1. 创建一个ServerSocket对象,指定口号,用于监听客户的连接请求。 2. 创建一个Socket对象,指定服务器的IP地址和口号,连接到服务器。 3. 在客户和服务器之间建立输入输出流,用于数据的传输。 4. 客户向服务器发送数据,服务器接收数据并处理。 5. 服务器向客户发送数据,客户接收数据并处理。 6. 当客户和服务器之间的通信结束时,关闭输入输出流和Socket对象。 7. 服务器继续监听客户的连接请求,直到程序结束。 具体的实现步骤可以参考以下代码: Client.java ``` import java.net.*; import java.io.*; public class Client { public static void main(String[] args) { try { // 连接服务器 Socket socket = new Socket("127.0.0.1", 8080); System.out.println("连接服务器成功!"); // 创建输入输出流 BufferedReader reader = new BufferedReader(new InputStreamReader(System.in)); OutputStream outputStream = socket.getOutputStream(); PrintWriter writer = new PrintWriter(outputStream); InputStream inputStream = socket.getInputStream(); BufferedReader input = new BufferedReader(new InputStreamReader(inputStream)); // 向服务器发送数据 String line = null; while ((line = reader.readLine()) != null) { writer.println(line); writer.flush(); if (line.equals("exit")) { break; } } // 关闭输入输出流和Socket对象 input.close(); outputStream.close(); writer.close(); reader.close(); socket.close(); } catch (Exception e) { e.printStackTrace(); } } } ``` Server.java ``` import java.net.*; import java.io.*; public class Server { public static void main(String[] args) { try { // 创建ServerSocket对象,指定口号 ServerSocket serverSocket = new ServerSocket(8080); System.out.println("服务器已经启动,等待客户连接..."); while (true) { // 监听客户的连接请求,等待连接 Socket socket = serverSocket.accept(); System.out.println("客户连接成功,IP地址为:" + socket.getInetAddress()); // 创建输入输出流 InputStream inputStream = socket.getInputStream(); BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream)); OutputStream outputStream = socket.getOutputStream(); PrintWriter writer = new PrintWriter(outputStream); // 读取客户发送的数据 String line = null; while ((line = reader.readLine()) != null) { System.out.println("客户发送的数据:" + line); writer.println("服务器已经接收到数据:" + line); writer.flush(); if (line.equals("exit")) { break; } } // 关闭输入输出流和Socket对象 reader.close(); outputStream.close(); writer.close(); socket.close(); } } catch (Exception e) { e.printStackTrace(); } } } ``` 这里是一个简单的Java Socket多客户Client-Server聊天程序的实现。你可以根据你的需求进行修改和扩展。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值