Home Java javaTutorial Share example code for handling sticky packets during socket communication in Java

Share example code for handling sticky packets during socket communication in Java

May 27, 2017 am 09:59 AM

This article mainly introduces the situation of sticky packets in the process of socket communication in java. It has certain reference value. Interested friends can refer to it.

I have learned about processing in java in the past two days. The situation of packet sticking during socket communication is very important, so I will add a few notes today.

The sticky package processing program is the client's message receiving thread:

Client:

import java.io.InputStream; 
import java.io.InputStreamReader; 
import java.io.OutputStreamWriter; 
import java.io.PrintWriter; 
import java.io.Reader; 
import java.net.Socket; 
import java.nio.CharBuffer; 
 
public class TestSocketClient { 
 
   
  public static void main(String[] args) { 
    // TODO Auto-generated method stub 
     
    new TestSocketClient().start(); 
  } 
  class SendThread extends Thread{ 
    private Socket socket; 
    public SendThread(Socket socket){ 
      this.socket=socket; 
    } 
    @Override 
    public void run(){ 
      while(true){ 
        try{ 
          Thread.sleep(1000);  
          String send="<SOAP-ENV:Envelope>"+System.currentTimeMillis()+"</SOAP-ENV:Envelope>"; 
          PrintWriter pw=new PrintWriter(new OutputStreamWriter(socket.getOutputStream())); 
          pw.write(send); 
          pw.flush(); 
        }catch(Exception e){ 
          e.printStackTrace(); 
        } 
      } 
    } 
  } 
  class ReceiveThread extends Thread{ 
    private Socket socket; 
    private volatile byte[] bytes=new byte[0]; 
    public ReceiveThread(Socket socket){ 
      this.socket=socket; 
    } 
    public byte[] mergebyte(byte[] a,byte[] b,int begin,int end){ 
      byte[] add=new byte[a.length+end-begin]; 
      int i=0; 
      for(i=0;i<a.length;i++){ 
        add[i]=a[i]; 
      } 
      for(int k=begin;k<end;k++,i++){ 
        add[i]=b[k]; 
      } 
      return add; 
    } 
    @Override 
    public void run(){ 
      while(true){ 
        try{ 
          InputStream reader=socket.getInputStream(); 
          if(bytes.length<2){ 
            byte[] head=new byte[2-bytes.length]; 
            int couter=reader.read(head); 
            if(couter<0){ 
              continue; 
            } 
            bytes=mergebyte(bytes,head,0,couter); 
            if(couter<2){ 
              continue; 
            } 
          } 
          //下面这个值请注意,一定要取2长度的字节子数组作为报文长度,你懂得 
          byte[] temp=new byte[0]; 
          temp=mergebyte(temp,bytes,0,2); 
          String templength=new String(temp); 
          int bodylength=Integer.parseInt(templength);       
          if(bytes.length-2<bodylength){ 
            byte[] body=new byte[bodylength+2-bytes.length]; 
            int couter=reader.read(body); 
            if(couter<0){ 
              continue; 
            } 
            bytes=mergebyte(bytes,body,0,couter); 
            if(couter<body.length){ 
              continue; 
            } 
          } 
          byte[] body=new byte[0]; 
          body=mergebyte(body, bytes, 2, bytes.length); 
          System.out.println("client receive body:  "+new String(body)); 
          bytes=new byte[0]; 
        }catch(Exception e){ 
          e.printStackTrace(); 
        } 
      } 
    } 
  } 
  public void start(){ 
    try{ 
    Socket socket=new Socket("127.0.0.1",18889); 
    new SendThread(socket).start(); 
    new ReceiveThread(socket).start(); 
    }catch(Exception e){ 
      e.printStackTrace(); 
    } 
     
  } 
}
Copy after login

Server:

package com.meituan.service.bankgate.gateway; 
 
/** 
 * Created by cqx on 16/7/19. 
 */ 
import java.io.*; 
import java.net.ServerSocket; 
import java.net.Socket; 
import java.nio.CharBuffer; 
import java.util.Date; 
 
public class TESTAHAHHA { 
 
  private final static String SOAP_BEGIN = "<SOAP-ENV:Envelope"; 
  private final static String SOAP_END = "</SOAP-ENV:Envelope>"; 
  public static void main(String[] args) { 
    // TODO Auto-generated method stub 
    TESTAHAHHA testserver=new TESTAHAHHA(); 
    testserver.start(); 
  } 
  public void start(){ 
    try{ 
      ServerSocket serversocket=new ServerSocket(18889); 
      while(true){ 
        Socket socket=serversocket.accept(); 
        new SocketThread(socket).start(); 
      } 
    }catch(Exception e){ 
      e.printStackTrace(); 
    } 
 
  } 
  class SocketThread extends Thread{ 
    private Socket socket; 
    private String temp; 
    public SocketThread(Socket socket){ 
      this.socket=socket; 
    } 
    public Socket getsocket(){ 
      return this.socket; 
    } 
    public void setsocjet(Socket socket){ 
      this.socket=socket; 
    } 
 
    @Override 
    public void run(){ 
      try{ 
        Reader reader=new InputStreamReader(socket.getInputStream()); 
        // Writer writer=new PrintWriter(new OutputStreamWriter(socket.getOutputStream(),"UTF-8")); 
        OutputStream writer=socket.getOutputStream(); 
        CharBuffer charbuffer=CharBuffer.allocate(8192); 
        int readindex=-1; 
        while((readindex=reader.read(charbuffer))!=-1){ 
          charbuffer.flip(); 
          temp+=charbuffer.toString(); 
          if(temp.indexOf(SOAP_BEGIN)!=-1 && temp.indexOf(SOAP_END)!=-1){ 
            //System.out.println(new Date().toLocaleString()+"server:"+temp); 
            temp=""; 
            String str="receive the soap message hahahah"; 
            byte[] headbytes=str.getBytes(); 
            int length=headbytes.length; 
            String l=String.valueOf(length); 
            byte[] lengthbytes=l.getBytes(); 
            byte[] bytes=new byte[length+lengthbytes.length]; 
            int i=0; 
            for(i=0;i<lengthbytes.length;i++){ 
              bytes[i]=lengthbytes[i]; 
            } 
            for(int j=i,k=0;k<length;k++,j++){ 
              bytes[j]=headbytes[k]; 
            } 
            System.out.println("server send:"+new String(bytes)); 
            writer.write(bytes); 
            writer.flush(); 
          }else if(temp.indexOf(SOAP_BEGIN)!=-1){ 
            temp=temp.substring(temp.indexOf(SOAP_BEGIN)); 
          } 
          if(temp.length()>1024*16){ 
            break; 
          } 
        } 
      }catch(Exception e){ 
        e.printStackTrace(); 
      }finally{ 
        if(socket!=null){ 
          try{ 
            if(!socket.isClosed()){ 
              socket.close(); 
            } 
          }catch(Exception e){ 
            e.printStackTrace(); 
          } 
        } 
      } 
    } 
  } 
 
}
Copy after login

[Related recommendations]

1. An example tutorial on communication between java and php through socket

2. Detailed explanation of WebSocket and example code in HTML5

3. Common socket error summary

4. Summary of the difference between socket and http

The above is the detailed content of Share example code for handling sticky packets during socket communication in Java. For more information, please follow other related articles on the PHP Chinese website!

Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Article

R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
2 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
Repo: How To Revive Teammates
1 months ago By 尊渡假赌尊渡假赌尊渡假赌
Hello Kitty Island Adventure: How To Get Giant Seeds
4 weeks ago By 尊渡假赌尊渡假赌尊渡假赌

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

Square Root in Java Square Root in Java Aug 30, 2024 pm 04:26 PM

Guide to Square Root in Java. Here we discuss how Square Root works in Java with example and its code implementation respectively.

Perfect Number in Java Perfect Number in Java Aug 30, 2024 pm 04:28 PM

Guide to Perfect Number in Java. Here we discuss the Definition, How to check Perfect number in Java?, examples with code implementation.

Random Number Generator in Java Random Number Generator in Java Aug 30, 2024 pm 04:27 PM

Guide to Random Number Generator in Java. Here we discuss Functions in Java with examples and two different Generators with ther examples.

Weka in Java Weka in Java Aug 30, 2024 pm 04:28 PM

Guide to Weka in Java. Here we discuss the Introduction, how to use weka java, the type of platform, and advantages with examples.

Armstrong Number in Java Armstrong Number in Java Aug 30, 2024 pm 04:26 PM

Guide to the Armstrong Number in Java. Here we discuss an introduction to Armstrong's number in java along with some of the code.

Smith Number in Java Smith Number in Java Aug 30, 2024 pm 04:28 PM

Guide to Smith Number in Java. Here we discuss the Definition, How to check smith number in Java? example with code implementation.

Java Spring Interview Questions Java Spring Interview Questions Aug 30, 2024 pm 04:29 PM

In this article, we have kept the most asked Java Spring Interview Questions with their detailed answers. So that you can crack the interview.

Break or return from Java 8 stream forEach? Break or return from Java 8 stream forEach? Feb 07, 2025 pm 12:09 PM

Java 8 introduces the Stream API, providing a powerful and expressive way to process data collections. However, a common question when using Stream is: How to break or return from a forEach operation? Traditional loops allow for early interruption or return, but Stream's forEach method does not directly support this method. This article will explain the reasons and explore alternative methods for implementing premature termination in Stream processing systems. Further reading: Java Stream API improvements Understand Stream forEach The forEach method is a terminal operation that performs one operation on each element in the Stream. Its design intention is

See all articles