In addition to Weibo, there is also WeChat
Please pay attention
WeChat public account
Shulou
2025-02-25 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >
Share
Shulou(Shulou.com)06/03 Report--
This article focuses on "Java implementation of the Http protocol", interested friends may wish to have a look. The method introduced in this paper is simple, fast and practical. Let's let the editor take you to learn "Java's method of implementing the Http protocol".
Catalogue
Java implements Http protocol
I. definition of protocol request
II. Definition of response protocol
III. Definition of coding constant
Fourth, the implementation of the client
Fifth, the realization of the server.
VI. Implementation of ProtocolUtils tool class
7. The implementation of ByteUtils class.
HTTP protocol belongs to the application layer protocol, which is built on top of TCP and IP protocols and is at the top of the TCP/IP protocol architecture layer. Therefore, it does not have to deal with the tedious details of the lower layer protocols, such as packet loss and reissue, handshake and data segmentation and reassembly, so that developers can focus on the application business.
Protocol is the specification of communication. In order to better understand the HTTP protocol, we can design a simple application layer communication protocol based on the Socket API interface of Java to simply analyze the process and details of the protocol implementation.
In our sample program today, the client will send a command to the server. After receiving the command, the server will determine whether the command is "HELLO". If it is "HELLO", the response returned by the server to the client is "hello". Otherwise, the response returned by the server to the client is "bye bye".
Next, we use Java to implement this simple application layer communication protocol.
I. definition of protocol request
The request of the protocol mainly includes three fields: code, command and command length.
Package com.binghe.params;/** * definition of protocol request * @ author binghe * * / public class Request {/ * Protocol Encoding * / private String command; / * Command length * / private int commandLength; public Request () {super ();} public Request (byte encode, String command, int commandLength) {super (); this.encode = encode; this.command = command This.commandLength = commandLength;} public byte getEncode () {return encode;} public void setEncode (byte encode) {this.encode = encode;} public String getCommand () {return command;} public void setCommand (String command) {this.command = command;} public int getCommandLength () {return commandLength;} public void setCommandLength (int commandLength) {this.commandLength = commandLength } @ Override public String toString () {return "Request [encode=" + encode + ", command=" + command + ", commandLength=" + commandLength + "]";}} II. Definition of response protocol
The response of the protocol mainly includes three fields: coding, response content and response length.
Package com.binghe.params;/** * definition of protocol response * @ author binghe * / public class Response {/ * Encoding * / private byte encode; / * response content * / private String response; / * response length * / private int responseLength; public Response () {super ();} public Response (byte encode, String response, int responseLength) {super (); this.encode = encode; this.response = response This.responseLength = responseLength;} public byte getEncode () {return encode;} public void setEncode (byte encode) {this.encode = encode;} public String getResponse () {return response;} public void setResponse (String response) {this.response = response;} public int getResponseLength () {return responseLength;} public void setResponseLength (int responseLength) {this.responseLength = responseLength } @ Override public String toString () {return "Response [encode=" + encode + ", response=" + response + ", responseLength=" + responseLength + "]";}} III. Coding constant definition
The definition of coding constant mainly includes UTF-8 and GBK coding.
Package com.binghe.constant;/** * constant class * @ author binghe * * / public final class Encode {/ / UTF-8 encoding public static final byte UTF8 = 1; / / GBK encoding public static final byte GBK = 2;} IV. Implementation of the client
The client first constructs a request request, sends it to the remote end through the Socket interface, receives the response information from the remote end, and constructs a Response object.
Package com.binghe.protocol.client;import java.io.IOException;import java.io.InputStream;import java.io.OutputStream;import java.net.Socket;import com.binghe.constant.Encode;import com.binghe.params.Request;import com.binghe.params.Response;import com.binghe.utils.ProtocolUtils;/** * client code * @ author binghe * * / public final class Client {public static void main (String [] args) throws IOException {/ / request Request request = new Request () Request.setCommand ("HELLO"); request.setCommandLength (request.getCommand (). Length ()); request.setEncode (Encode.UTF8); Socket client = new Socket ("127.0.0.1", 4567); OutputStream out = client.getOutputStream (); / / send request ProtocolUtils.writeRequest (out, request); / / read response data InputStream in = client.getInputStream (); Response response = ProtocolUtils.readResponse (in) System.out.println ("the response result information obtained is:" + response.toString ());}} V. Implementation of the server
The server receives the request from the client and responds to different message information according to the receiving command. If it is a "HELLO" command, it responds to "hello" information, otherwise it responds to "bye bye" information.
Package com.binghe.protocol.server;import java.io.IOException;import java.io.InputStream;import java.io.OutputStream;import java.net.ServerSocket;import java.net.Socket;import com.binghe.constant.Encode;import com.binghe.params.Request;import com.binghe.params.Response;import com.binghe.utils.ProtocolUtils;/** * Server side code * @ author binghe * * / public final class Server {public static void main (String [] args) throws IOException {ServerSocket server = new ServerSocket (4567) While (true) {Socket client = server.accept (); / / read request data InputStream input = client.getInputStream (); Request request = ProtocolUtils.readRequest (input); System.out.println ("request parameters received are:" + request.toString ()); OutputStream out = client.getOutputStream (); / / Assembly response data Response response = new Response (); response.setEncode (Encode.UTF8) If ("HELLO" .equals (request.getCommand () {response.setResponse ("hello");} else {response.setResponse ("bye bye");} response.setResponseLength (response.getResponse (). Length ()); ProtocolUtils.writeResponse (out, response);} implementation of ProtocolUtils tool class
The readRequest method of ProtocolUtils reads the encode, command and commandLength parameters of the request from the input stream passed in, carries on the corresponding coding conversion, and constructs the Request object to return. The writeResponse method writes the fields of the response object to the output stream of the response according to the corresponding encoding.
There is one detail to pay attention to: if an int type is written directly into OutputStream, its lower 8 bits will be intercepted and its high 24 bits will be discarded, so the corresponding conversion operation will be required when transmitting and receiving data.
Package com.binghe.utils;import java.io.IOException;import java.io.InputStream;import java.io.OutputStream;import com.binghe.constant.Encode;import com.binghe.params.Request;import com.binghe.params.Response / * * Protocol utility class * @ author binghe * * / public final class ProtocolUtils {/ * deserialize Request objects from the input stream * @ param input * @ return * @ throws IOException * / public static Request readRequest (InputStream input) throws IOException {/ / read encoding byte [] encodeByte = new byte [1]; input.read (encodeByte); byte encode = encodeByte [0] / / read command length byte [] commandLengthBytes = new byte [4]; input.read (commandLengthBytes); int commandLength = ByteUtils.byte2Int (commandLengthBytes); / / read command byte [] commandBytes = new byte [commandLength]; input.read (commandBytes); String command = ""; if (Encode.UTF8 = = encode) {command = new String (commandBytes, "UTF-8");} else if (Encode.GBK = = encode) {command = new String (commandBytes, "GBK") } / / Assembly request returns Request request = new Request (encode, command, commandLength); return request;} / * deserializes Response objects from the input stream * @ param input * @ return * @ throws IOException * / public static Response readResponse (InputStream input) throws IOException {/ / read encoding byte [] encodeByte = new byte [1]; input.read (encodeByte); byte encode = encodeByte [0] / / read response length byte [] responseLengthBytes = new byte [4]; input.read (responseLengthBytes); int responseLength = ByteUtils.byte2Int (responseLengthBytes); / / read the command byte [] responseBytes = new byte [responseLength]; input.read (responseBytes); String response = ""; if (Encode.UTF8 = = encode) {response = new String (responseBytes, "UTF-8");} else if (Encode.GBK = = encode) {response = new String (responseBytes, "GBK") } / / the assembly request returns Response resp = new Response (encode, response, responseLength); return resp;} / * * serialization request information * @ param output * @ param response * / public static void writeRequest (OutputStream output, Request request) throws IOException {/ / return the response response to the client output.write (request.getEncode ()); / / output.write (response.getResponseLength ()) Directly write an int type will intercept the lower 8-bit transmission and discard the high 24-bit output.write (ByteUtils.int2ByteArray (request.getCommandLength ()); if (Encode.UTF8 = = request.getEncode ()) {output.write (request.getCommand (). GetBytes ("UTF-8"));} else if (Encode.GBK = = request.getEncode ()) {output.write (request.getCommand (). GetBytes ("GBK"));} output.flush () } / * Serialization response information * @ param output * @ param response * / public static void writeResponse (OutputStream output, Response response) throws IOException {/ / return the response response to the client output.write (response.getEncode ()); / / output.write (response.getResponseLength ()); directly write an int type will intercept the lower 8-bit transmission and discard the high 24-bit output.write (ByteUtils.int2ByteArray (response.getResponseLength () If (Encode.UTF8 = = response.getEncode ()) {output.write (response.getResponse (). GetBytes ("UTF-8"));} else if (Encode.GBK = = response.getEncode ()) {output.write (response.getResponse (). GetBytes ("GBK"));} output.flush ();} 7. Implementation package com.binghe.utils of ByteUtils class / * Byte conversion tool class * @ author binghe * / public final class ByteUtils {/ * convert byte array to int number * @ param bytes * @ return * / public static int byte2Int (byte [] bytes) {int num = bytes [3] & 0xFF; num | = (bytes [2] > 16) & 0xFF); result [2] = (byte) ((I > > 8) & 0xFF) Result [3] = (byte) (I & 0xFF); return result;}} at this point, I believe you have a deeper understanding of "Java's method of implementing Http protocol". You might as well do it in practice. Here is the website, more related content can enter the relevant channels to inquire, follow us, continue to learn!
Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.
Views: 0
*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.
Continue with the installation of the previous hadoop.First, install zookooper1. Decompress zookoope
"Every 5-10 years, there's a rare product, a really special, very unusual product that's the most un
© 2024 shulou.com SLNews company. All rights reserved.