Socket

package cardvalue.managementsystem.util;

import android.content.Context;
import java.io.BufferedWriter;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.io.PrintWriter;
import java.net.Socket;
import java.util.concurrent.Callable;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit;

/**
 * Created by Administrator on 2017/7/6.
 */

public class SendReceiveUtil {
    public static Socket socket = null;
    /**线程池,为了方便展示,此处直接采用线程池进行线程管理,而没有一个个开线程*/
    private ExecutorService executorService;
    private  OutputStream outputStream;
    private InputStream inputStream;
    public Context context;

    public SendReceiveUtil(Context context) throws IOException {
        super();
        this.context = context;
        /**初始化线程池*/
        executorService = Executors.newCachedThreadPool();
        start();
        /**
         * 这个线程是每隔多少秒执行一次,执行发现断开了就重连
         */
        ScheduledExecutorService server = Executors.newScheduledThreadPool(1);
        server.schedule(new Runnable() {
            public void run() {
                isConnect();
            }
        },10, TimeUnit.SECONDS);
    }

    //发送数据
    public  void sendData(String data){
        // outputStream.write(data.getBytes()); 原来的
        PrintWriter out1= new PrintWriter(new BufferedWriter(new OutputStreamWriter(
            outputStream)), true);
        out1.println(data+"<over>");
        /** 特别注意:数据的结尾加上换行符(<over>)才可让服务器端的readline()停止阻塞
         步骤3:发送数据到服务端*/
        try {
            outputStream.flush();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }



    //接收数据
    private StringBuffer str=new StringBuffer();
    private  InputStreamReader reader = null;
    public String receiveData() throws ExecutionException, InterruptedException {
       /* InputStream inputStream = socket.getInputStream();
//        DataInputStream data=new DataInputStream(inputStream);
        byte[] buf = new byte[1024];
        int len = inputStream.read(buf);
        String text = new String(buf, 0, len);*/
        Future<String> fu =executorService.submit(new Callable<String> () {

            @Override
            public String call() throws Exception {
                try {
                    reader = new InputStreamReader(inputStream);
                    while (true){
                        char[] ct = new char[8*1024];
                        int count = reader.read(ct,0,1024*8);
                        str.append(new String(ct,0,count));
                        if(str.toString().indexOf("<over>")>=0){
                            str=new StringBuffer(str.toString().replace("<over>",""));
                            break;
                        }
                    }
                    System.out.println(str.toString());
                } catch (IOException e) {
                    e.printStackTrace();
                }
                return str.toString();
            }
        });

        return fu.get();
    }



    /**检测是否连接 如果断开就重连*/
    public boolean isConnect(){
        /**检测是否关闭状态*/
        if(socket.isClosed()){
            //TODO 这个地方检测数 是断开,在这写重连的方法。
         /*   executorService.execute(new Runnable() {
                @Override
                public void run() {
                    try {
                        *//** 创建Socket对象 & 指定服务端的IP 及 端口号*//*
                        socket = new Socket("192.168.16.20", 12345);
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                }
            });*/
            start();
            return false;
        }
        return true;
    }


    /**断开连接*/
    public void closeConnect(){
        try {
            socket.close();
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    }



    public void start(){
        executorService.execute(new Runnable() {
            @Override
            public void run() {
                try {
                    /** 创建Socket对象 & 指定服务端的IP 及 端口号*/
                    socket = new Socket("192.168.16.20", 12345);
                    outputStream = socket.getOutputStream();
                    inputStream=socket.getInputStream();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        });
    }
}

package cardvalue.managementsystem;

import android.app.Application;
import cardvalue.managementsystem.util.SendReceiveUtil;
import java.io.IOException;

/**
 * Created by Administrator on 2017/7/7.
 */

public class MyApplication  extends Application{

    public SendReceiveUtil sendReceiveUtil;

    public SendReceiveUtil getSendReceiveUtil() {
        return sendReceiveUtil;
    }

    private static MyApplication mInstance = null;
    @Override
    public void onCreate() {
        super.onCreate();
        mInstance = this;
        try {
            sendReceiveUtil=new SendReceiveUtil(getApplicationContext());
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    public static MyApplication getInstance() {
        return mInstance;
    }



}

package cardvalue.managementsystem.activity;

import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import cardvalue.managementsystem.MyApplication;
import cardvalue.managementsystem.R;
import cardvalue.managementsystem.pojo.BaseMessage;
import cardvalue.managementsystem.util.SendReceiveUtil;
import java.io.IOException;
import java.util.concurrent.ExecutionException;

public class Main3Activity extends AppCompatActivity {



    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main3);
        BaseMessage msg1 = new BaseMessage();
        msg1.setCmdType(1);
        msg1.setFrom(1);
        msg1.setMsg("weiweina;123456789");
        msg1.setTo(new int[]{});

        MyApplication.getInstance().getSendReceiveUtil().sendData(msg1.toJson());
        try {
            MyApplication.getInstance().getSendReceiveUtil().receiveData();
        } catch (ExecutionException e) {
            e.printStackTrace();
        } catch (InterruptedException e) {
            e.printStackTrace();
        }


    }
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值