编程知识 cdmana.com

Half an hour to achieve java hands-on HTTP protocol, cool!

Hello everyone , I'm glacier ~~

A lot of kids told me , It's so hard to learn the Internet , What do I do ? In fact, many technologies are interlinked , As long as you understand the nature of Technology , You can do it yourself . see , Glaciers take advantage of the weekend , Only a few Java Class is simply implemented Http agreement , Shuang !! Like it, guys , Collection , Comment on , Let's go ~~

HTTP Protocol belongs to application layer protocol , It is built on TCP and IP The agreement above , be in TCP/IP Top of the protocol architecture layer , therefore , It doesn't need to deal with lower layer protocols, such as packet loss reissue 、 Handshake and data segmentation and reassembly and other tedious details , So that developers can focus on the application business .

Protocol is the standard of communication , For better understanding HTTP agreement , We can base it on Java Of Socket API Interface , By designing a simple application layer communication protocol , Let's analyze the process and details of protocol implementation .

In our sample program today , The client will send a command to the server , After the server receives the command , Will determine if the command is “HELLO”, If it is “HELLO”, Then the response returned by the server to the client is “hello”, otherwise , The response from the server to the client is “bye bye”.

Let's use Java Implement this simple application layer communication protocol , Do as you say , Walk up ~~

Definition of protocol request

The request of the agreement mainly includes : code 、 Command and command length three fields .

package com.binghe.params;
/**
 *  Definition of protocol request
 * @author binghe
 *
 */

public class Request {
 /**
  *  Protocol code
  */

 private byte encode;
 
 /**
  *  command
  */

 private String command;
 
 /**
  *  The 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 + "]";
 }
 
}

The definition of response protocol

The response of the protocol mainly includes : code 、 Response content and response length .

package com.binghe.params;

/**
 *  Definition of protocol response
 * @author binghe
 *
 */

public class Response {
 /**
  *  code
  */

 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 + "]";
 }
 
}

Code constant definition

The definition of coding constant mainly includes UTF-8 and GBK Two codes .

package com.binghe.constant;

/**
 *  Constant class
 * @author binghe
 *
 */

public final class Encode {
 //UTF-8 code
 public static final byte UTF8 = 1;
 //GBK code
 public static final byte GBK = 2;
}

The implementation of client

The client first constructs a request request , adopt Socket The interface sends it to the far end , And receive the remote response information , And construct 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 a 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());
 }
}

Server-side implementation

The server receives the request from the client , Depending on the command received , Respond to different message information , If it is “HELLO” command , The response “hello” Information , Otherwise respond “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 End 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(" The received request parameter is : " + 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);
  }
 }
}

ProtocolUtils Implementation of the utility class

ProtocolUtils Of readRequest Method will read the requested... From the incoming input stream encode、command and commandLength Three parameters , Carry out corresponding coding transformation , Constructed as Request Object returns . and writeResponse The way is to response The fields of the object are written to the output stream of the response according to the corresponding encoding .

There's one detail that needs to be focused on :OutputStream Write a int type , Will intercept its low 8 position , Discard its height 24 position , therefore , When transmitting and receiving data , The corresponding transformation operation is needed .

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 tool class
 * @author binghe
 *
 */

public final class ProtocolUtils {
 /**
  *  Deserialize from the input stream Request object
  * @param input
  * @return
  * @throws IOException
  */

 public static Request readRequest(InputStream input) throws IOException{
  // Read the code
  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");
  }
  // The assembly request returns
  Request request = new Request(encode, command, commandLength);
  return request;
 }
 /**
  *  Deserialize from the input stream Response object
  * @param input
  * @return
  * @throws IOException
  */

 public static Response readResponse(InputStream input) throws IOException{
  // Read the code
  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 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;
 }
 
 /**
  *  Serialize request information
  * @param output
  * @param response
  */

 public static void writeRequest(OutputStream output, Request request) throws IOException{
  // take response The response is returned to the client
  output.write(request.getEncode());
  //output.write(response.getResponseLength()); direct write One int Type will intercept low 8 Bit transfer drop High 24 position
  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();
 }
 /**
  *  Serialize response information
  * @param output
  * @param response
  */

 public static void writeResponse(OutputStream output, Response response) throws IOException{
  // take response The response is returned to the client
  output.write(response.getEncode());
  //output.write(response.getResponseLength()); direct write One int Type will intercept low 8 Bit transfer drop High 24 position
  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();
 }
}

ByteUtils The realization of the class

package com.binghe.utils;

/**
 *  Byte conversion tool class
 * @author binghe
 *
 */

public final class ByteUtils {
 /**
  *  take byte Array to int Numbers
  * @param bytes
  * @return
  */

 public static int byte2Int(byte[] bytes){
  int num = bytes[3] & 0xFF;
  num |= ((bytes[2] << 8) & 0xFF00);
  num |= ((bytes[1] << 16) & 0xFF0000);
  num |= ((bytes[0] << 24) & 0xFF000000);
  return num;
 }
 
 /**
  *  take int The type number is converted to byte Array
  * @param num
  * @return
  */

 public static byte[] int2ByteArray(int i){
  byte[] result = new byte[4];
  result[0]  = (byte)(( i >> 24 ) & 0xFF);
  result[1]  = (byte)(( i >> 16 ) & 0xFF);
  result[2]  = (byte)(( i >> 8 ) & 0xFF);
  result[3]  = (byte)(i & 0xFF);
  return result;
 }
}

thus , Our application layer communication protocol sample code development is completed , What about? , friends , Isn't that easy ? Open up your environment , Hand roll Http Make an agreement !!

Okay , That's all for today , I'm glacier , If you have any questions, please leave a message below , I can also add wechat :sun_shine_lyz, I'll pull you into the group , Exchange technology together , Step up together , Go into the big factory together ~~

版权声明
本文为[glacier]所创,转载请带上原文链接,感谢
https://cdmana.com/2021/05/20210525004024503Q.html

Scroll to Top