• 大小: 5KB
    文件类型: .java
    金币: 1
    下载: 0 次
    发布日期: 2021-05-12
  • 语言: Java
  • 标签: socket  

资源简介

Implementation 'com.tonystark.android:socket:+'基础上写的socket使用工具传输字节和字符串

资源截图

代码片段和文件信息

package com.cesi.oritest;

import java.io.BufferedWriter;
import java.io.DataInputStream;
import java.io.IOException;
import java.io.OutputStreamWriter;
import java.net.InetSocketAddress;
import java.net.Socket;

/**
 * Created by xiaodukai on 2018/11/14.
 */

public class TcpHelper {
    private Socket socket;
    private BufferedWriter  bufferedWriter;
    private DataInputStream inputStream;
    private boolean NeedStop;
    private InetSocketAddress SerAddr;
    public  String ErrMsg;
    private ReadThread readThread;           //读取数据线程
    private OnReceiveEvent receiveEvent;     //此事件用于当接收到数据时向主线程通知接收到的数据
    private long LastCheckTime;
    public static interface OnReceiveEvent{
        public  void ReceiveBytes(byte[] iData);
        public  void ReceiveString(String iData);
    }
    public enum EDataType{EDT_BYTEEDT_STRING};
    private EDataType dataType;
    public TcpHelper(String HostIpint HostPort) {
        try {
            LastCheckTime=System.currentTimeMillis();
            readThread =new ReadThread();
            NeedStop=false;
            SerAddr =  new InetSocketAddress(HostIpHostPort);
            NeedStop=false;
            socket = new Socket();
            readThread.start();
        }catch (Exception e)
        {
            ErrMsg=e.getMessage();
        }
    }
    public void SendString(String iText){       //发送字符串
        dataType=EDataType.EDT_STRING;
        toSend(iText);
    }
    public void SendBytes(byte[] iBuf){     //发送字节流指令
        dataType=EDataType.EDT_BYTE;
        String iText = new  String(iBuf);
        toSend(iText);
    }
    public void close(){
        if(socket!=null){
            try {
                socket.close();
                readThread.stop();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
    //发送数据线程
    private void toSend(final String iText){
        new Thread(
                new Runnable() {
                    @Override
                    public void run() {
                        try {
                            bufferedWriter.write(iText);
                            bufferedWriter.flush();
                        } catch (Exception e) {
                            e.printStackTrace();
                        }
                    }
                }
        ).start();
    }
    public boolean isConnected(){
        if(socket==null) return false;
        return socket.isConnected();
    }
 

评论

共有 条评论