Java socket solves half-packet, sticky-packet problem

Source: Internet
Author: User
Tags pack static class stringbuffer
Java socket solves half-packet, sticky-packet problemFirst, the Java socket half packet, sticky problem reasons and solutions See blog: http://www.cnblogs.com/solq/p/4315763.html http://bbs.csdn.net/topics/250027309? page=2 http://blog.csdn.net/pi9nc/article/details/17165171
Second, Java socket half Pack, sticky solution 1, with special strings such as/R,/n as the end of the data, so you can distinguish the packet. 2, send the request package when sending only fixed-length packets, so that the server received data can only receive fixed-length data, this method is too inefficient, not too suitable for frequent packet requests. 3, on the basis of TCP protocol to encapsulate a layer of data request protocol, packet = packet length + packet content, so that the server can know the length of each packet, you can solve the half packet, sticky problem Three, Java socket half packet, sticky problem recurrence, the code is as follows
Package org.weir.socket.socketPackage;
Import java.io.IOException;
Import Java.io.InputStream;
Import Java.io.OutputStream;
Import java.net.InetSocketAddress;
Import Java.net.ServerSocket;

Import Java.net.Socket; public class Sockettest {public static void main (string[] args) throws IOException, interruptedexception{new Socketse
		RVer (). Start ();
	New Socketclient (). Start ();
		Static class Socketclient extends thread{socket clientsocket = new socket ();
		Public Socketclient () throws ioexception{Clientsocket.connect (new Inetsocketaddress (8089)); public void Run () {String reqmessage = ' HelloWorld.
			From Clientsocket It is Test half packages! ";
					try {for (int i=0;i<10;i++) {outputstream OS = Clientsocket.getoutputstream ();
					Os.write (Reqmessage.getbytes ());
				SYSTEM.OUT.PRINTLN ("Send Message" +i+ "" +reqmessage);
			The catch (IOException e) {//TODO auto-generated catch block E.printstacktrace (); }finally{if (clientsocket != null) {try {clientsocket.close ();
					catch (IOException e) {//TODO auto-generated catch block E.printstacktrace ();
		"}}}} Static class Socketserver extends thread{serversocket serversocket;
				Public socketserver () {try {serversocket = new ServerSocket ();
			Serversocket.bind (New Inetsocketaddress (8089));
			catch (IOException e) {//TODO auto-generated catch block E.printstacktrace ();
			} public void Run () {int count = 0;
			Socket socket = NULL;
			try {socket = serversocket.accept ();
			catch (IOException E1) {//TODO auto-generated catch block E1.printstacktrace ();
					} while (true) {try {byte[] Bytebuffer = new BYTE[50];
					StringBuffer receivbuffer = new StringBuffer ();
					InputStream reader = Socket.getinputstream ();
					Count = Reader.read (Bytebuffer);
						if (count>0) {receivbuffer.append (new String (Bytebuffer,0,count)); System.out.println("Receive data from client:" +receivbuffer.tostring ());
				Count = 0;
				catch (IOException e) {//TODO auto-generated catch block E.printstacktrace ();
 }
			}
		}
	}
The results of the implementation are as follows:
A total of 10 packets were sent because the received buffer was 50 bytes, so there was a case where a full package could not be received, and a half packet and a sticky packet occurred. Four, Java socket to solve the problem of half packet, sticky package.
Package org.weir.socket.socketPackage;
Import java.io.IOException;
Import Java.io.OutputStream;
Import Java.io.OutputStreamWriter;
Import Java.io.PrintWriter;
Import java.net.InetSocketAddress;
Import Java.net.Socket; /** * Socket Solution Half pack problem adopts package body length (two bytes) + Package contents to disassemble package * @author Weir * September 19, 2017 PM 4:31:36/public class Clientsocket {public St
		atic void Main (String args[]) throws IOException {socket clientsocket = new socket ();
		Clientsocket.connect (New Inetsocketaddress (8089));

	New Sendthread (Clientsocket). Start ();
		Static Class Sendthread extends Thread {socket socket;

		PrintWriter printwriter = null;
			Public sendthread (socket socket) {this.socket = socket;
			try {printwriter = new PrintWriter (New OutputStreamWriter (Socket.getoutputstream ()));
			catch (IOException e) {//TODO auto-generated catch block E.printstacktrace (); @Override public void Run () {String reqmessage = "HelloWorld.
	From Clientsocket It is Test half packages! ";		for (int i = 0; i < i++) {sendpacket (reqmessage);
				} if (socket!= null) {try {socket.close ();
				catch (IOException e) {//TODO auto-generated catch block E.printstacktrace (); }} public void Sendpacket (String message) {//byte[] contentbytes = message.getbytes ()//package body content//int con Tentlength = contentbytes.length;//Package length//String head = string.valueof (contentlength);//header content//byte[] Headbytes =
Head.getbytes ();//header content byte array//byte[] bytes = new Byte[headbytes.length + contentlength];//package = Baotou + package body/int i = 0; for (i = 0; i < headbytes.length i++) {//Baotou//bytes[i] = headbytes[i];//}//for (int j = i, k = 0; k < ContentLength;				k++, J + +) {//inclusion//BYTES[J] = contentbytes[k];//} try {outputstream writer = Socket.getoutputstream ();//
				Writer.write (bytes);
				Writer.write (Message.getbytes ());
			Writer.flush (); catch (IOException e) {//TODO auto-generated catch blocK E.printstacktrace ();
 }
		}
	}

}

Package org.weir.socket.socketPackage;
Import java.io.IOException;
Import Java.io.InputStream;
Import java.net.InetSocketAddress;
Import Java.net.ServerSocket;
Import Java.net.Socket; * * Packet=packethead+content * read out the length of the package, read out the package, not enough to read * * public class Socketserver {public static void main (String ar
		Gs[]) {ServerSocket serversocket;
			try {serversocket = new ServerSocket ();
			Serversocket.bind (New Inetsocketaddress (8089));
				while (true) {Socket socket = serversocket.accept ();

			New Receivethread (socket). Start ();
		The catch (IOException e) {//TODO auto-generated catch block E.printstacktrace (); } static class Receivethread extends Thread {public static final int packet_head_length=2;//header length private Socket
		Socket

		Private volatile byte[] bytes = new Byte[0];
		Public receivethread (socket socket) {this.socket = socket; 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 () {int count = 0;
					while (true) {try {InputStream reader = Socket.getinputstream ();
						if (Bytes.length < packet_head_length) {byte[] head = new Byte[packet_head_length-bytes.length];
						int couter = Reader.read (head);
						if (Couter < 0) {continue;
						} bytes = Mergebyte (bytes, head, 0, Couter);
						if (Couter < packet_head_length) {continue;
					The following value please note that you must take the byte array of 2 length as the message length, you know byte[] temp = new Byte[0];
					temp = mergebyte (temp, Bytes, 0, packet_head_length);
					String templength = new String (temp);
						int bodylength = Integer.parseint (templength);//Package length if (Bytes.length-packet_head_length < bodylength) {//Not enough for a package byte[] BODY = new Byte[bodylength + packet_head_length-bytes.length];//the remaining bytes should be read (gather together a packet) 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, packet_head_length, bytes.length);
					count++;
					SYSTEM.OUT.PRINTLN ("Server Receive body:" + count+new String (body));
				bytes = new Byte[0];
				catch (Exception e) {e.printstacktrace ();
 }
			}
		}
	}
}

The results are as follows:
Client sent a total of 100 data, the server side received a complete package.
Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.