(java)处理socket通信过程中粘包的情况

直接上代码吧:

处理粘包程序是客户端的接受消息线程:


客户端:

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=""+System.currentTimeMillis()+"";
					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

服务端:

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 = "1024*16){
                        break;
                    }
                }
            }catch(Exception e){
                e.printStackTrace();
            }finally{
                if(socket!=null){
                    try{
                        if(!socket.isClosed()){
                            socket.close();
                        }
                    }catch(Exception e){
                        e.printStackTrace();
                    }
                }
            }
        }
    }

}


你可能感兴趣的:((java)处理socket通信过程中粘包的情况)