/// <summary> /// 创建Socket,重复创建会释放之前的 /// </summary> public void OpenNewAdbSocket() { if (CurAdbSocket != null) { CurAdbSocket.Dispose(); } try { CurAdbSocket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp) { ReceiveTimeout = ConstCodeHelper.DEFAULT_TIMEOUT, SendTimeout = ConstCodeHelper.DEFAULT_TIMEOUT, ReceiveBufferSize = ConstCodeHelper.DEFAULT_COMMAND_BUFFER_SIZE }; CurAdbSocket.Connect(SocketAddress); CurAdbSocket.NoDelay = true; IsOpened = true; } catch (Exception ex) { LoggerManagerSingle.Instance.Error(ex); IsOpened = false; } }
/// <summary> /// 发送字节数据 /// </summary> /// <returns>是否发送成功【成功发送的字节数据小于0,则视为发送失败】</returns> public bool Write(byte[] data, int len = 0) { try { if (CurAdbSocket.Connected) { var count = CurAdbSocket.Send(data, len > 0 ? len : data.Length, SocketFlags.None); if (count > 0) { return(true); } } } catch (Exception ex) { LoggerManagerSingle.Instance.Error(ex); } return(false); }
/// <summary> /// 从socket中接收数据输出到接收器中 /// </summary> public void Read(AbstractOutputReceiver receiver, int bufSize) { CurAdbSocket.ReceiveBufferSize = bufSize; var data = new byte[bufSize]; int count = -1; try { while (count != 0) { count = CurAdbSocket.Receive(data); if (count <= 0) { break; } receiver.Add(data, 0, count); } } finally { receiver.Flush(); } }
/// <summary> /// 从socket中接收读取指定大小的数据流 /// </summary> public void Read(byte[] data, int length = -1) { int expLen = length < 0 ? data.Length : length; expLen = expLen > data.Length ? data.Length : expLen; CurAdbSocket.ReceiveBufferSize = expLen; int count = -1; int totalRead = 0; while (count != 0 && totalRead < expLen) { int left = expLen - totalRead; int buflen = left < CurAdbSocket.ReceiveBufferSize ? left : CurAdbSocket.ReceiveBufferSize; byte[] buffer = new byte[buflen]; count = CurAdbSocket.Receive(buffer, buflen, SocketFlags.None); if (count > 0) { Array.Copy(buffer, 0, data, totalRead, count); totalRead += count; } } }
/// <summary> /// 读取所有数据 /// </summary> /// <returns></returns> public byte[] ReadToEnd() { List <byte> result = new List <byte>(); CurAdbSocket.ReceiveBufferSize = 1024 * 16; byte[] value = new byte[1024 * 16]; try { while (true) { var readLength = CurAdbSocket.Receive(value, value.Length, SocketFlags.None); if (readLength < 1) { break; } result.AddRange(value.Take(readLength)); } } catch (Exception ex) { LoggerManagerSingle.Instance.Error(ex); } return(result.ToArray()); }
/// <summary> /// 释放资源 /// </summary> public void Dispose() { CurAdbSocket.Close(); CurAdbSocket.Dispose(); }