关于socket 通信一个封装很好的类

最近在项目中,某个功能模块需要使用socket通信,之前都是自己手写的,代码复用性不好。

于是本着偷懒的原则,在网上找了下,发现下面的博文有个很好的封装,直接记录下

http://www.jianshu.com/p/16aed9c3ceee

主要就用到了2个类,TcpClient客户端(用于和服务端连接) 和 SocketTransceiver(用于接收和发送数据,和服务端进行交互)


public abstract class TcpClient implements Runnable{

    private  String IP;
    private int port;
    boolean connect = false;
    private SocketTransceiver transceiver;
    private Socket socket;
    public void connect(String IP, int port){
        this.IP = IP;
        this.port = port;
        new Thread(this).start();
    }

    @Override
    public void run() {
        try {
                transceiver = new SocketTransceiver() {
                @Override
                public void onReceive(String s) {
                    TcpClient.this.onReceive(s);
                }

                @Override
                public void onConnectBreak() {
                    TcpClient.this.onConnectBreak();
                }

                    @Override
                    public void onSendSuccess(String s) {
                        TcpClient.this.onSendSuccess(s);
                    }


                };
                socket = new Socket(IP, port);
                connect = true;
                
             
//            try{
//                  socket.sendUrgentData(0xFF); //发送心跳包
//            }catch(Exception ex){
//            	  this.onConnectFalied();
//                 Log.i("hemiy", ex.getMessage().toString());
//            }
                
                this.onConnectSuccess();
                transceiver.start(socket);
        } catch (IOException e) {
            this.onConnectFalied();
            e.printStackTrace();
        }
    }

    public  boolean isConnected(){
        return connect;
    }

    public void disConnected(){
        connect = false;
        if(transceiver!=null){
            transceiver.stop();
            transceiver=null;
        }
    }

    public SocketTransceiver getTransceiver(){
        return transceiver;
    }

   

    public abstract void onConnectSuccess();

    public abstract void onConnectBreak();

    public abstract void onReceive(String s);

    public abstract void onConnectFalied();

    public abstract void  onSendSuccess(String s);

}



/**
 * @author hemiy
 * 2016-11-23下午5:41:42
 */
public abstract class SocketTransceiver implements Runnable{

    private Socket socket;
    private InputStream inputStream;
    private OutputStream outputStream;
    private boolean runFlag = false;
    private BufferedReader br;
    private PrintWriter pw;

    public void start(Socket socket){
        this.socket = socket;
        runFlag = true;
        new Thread(this).start();
    }

    public void stop(){
        runFlag = false;    
        
        if(inputStream!=null){
        	try {
				inputStream.close();
			} catch (IOException e) {
				e.printStackTrace();
			}
        }
        
        if(outputStream!=null){
        	try {
				outputStream.close();
			} catch (IOException e) {
				e.printStackTrace();
			}
        }
        
        if(br!=null){
        	try {
				br.close();
			} catch (IOException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
        }
        
        
        if(socket!=null){
        	try {
				socket.close();
			} catch (IOException e) {
				e.printStackTrace();
			}
        }
        
       
    }

    @Override
    public void run() {
        try {
            inputStream = socket.getInputStream();
            outputStream = socket.getOutputStream();
        } catch (IOException e) {
            runFlag = false;
            e.printStackTrace();
        }
            

        while (runFlag){
  
            br= new BufferedReader(new InputStreamReader(inputStream));
            String content=null;
            try {
				while ((content = br.readLine()) != null) {  
				    // 每当读到来自服务器的数据之后,发送消息通知程序界面显示该数据  
				 this.onReceive(content); 
				}
			} catch (IOException e) {
				e.printStackTrace();
			} 
        }

    }

    public void sendMSG(String s){
        if( outputStream != null){
            try {
                pw = new PrintWriter( new BufferedWriter(new OutputStreamWriter(outputStream)));  
                pw.println(s);// 发起报警参数
                pw.flush(); 
                
                this.onSendSuccess(s);
            } catch (Exception e) {
                onConnectBreak();
                runFlag = false;
                e.printStackTrace();
            }finally{
            
//            	if(pw!=null){
//            		pw.close();
//            	}
            	
            }
        }

    }

    public abstract void onReceive(String s);

    public abstract void onConnectBreak();

    public abstract void onSendSuccess(String s);

}





你可能感兴趣的:(关于socket 通信一个封装很好的类)