本文主要是介绍Android客户端TCP传输数据、重连、心跳检测,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!
1.Tcp连接、发送数据、接收数据工具类
public class TcpUtil {public static final int PORT = 9000;public static final String HOST = "192.168.2.127";public static Socket socket;private static TcpUtil utils = null;public static TcpUtil getInstance(Context context) {if (utils == null) {synchronized (TcpUtil.class) {if (utils == null) {utils = new TcpUtil(context);}}}return utils;}PreferencesUtil p;public TcpUtil(Context context) {socket = new Socket();SocketAddress socAddress = new InetSocketAddress(HOST, PORT);try {socket.connect(socAddress, 3000);Log.i("ds>>>", " 連接成功");} catch (IOException e) {e.printStackTrace();if (p == null)p = new PreferencesUtil(context, "stats");p.setState(false);utils = null;Log.i("ds>>>", " 連接失败");}}/*** 设置超时时间,该方法必须在bind方法之后使用.*/public void setSoTimeout(final int timeout) throws Exception {socket.setSoTimeout(timeout);}/*** 获得超时时间.*/public int getSoTimeout() throws Exception {return socket.getSoTimeout();}public final Socket getSocket() {return socket;}/*** 向指定的服务端发送数据信息.*/public final OutputStream send(final byte[] data) throws IOException {OutputStream o =
这篇关于Android客户端TCP传输数据、重连、心跳检测的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!