/// <summary> /// Connections the forwarding thread. /// </summary> /// <param name="from">From.</param> /// <param name="to">To.</param> private void ConnForwardingThread(int from, int to) { byte[] recv_buf = new byte[256]; int bytes_recv, bytes_send; while (true) { bytes_recv = MobileDevice.recv(from, recv_buf, 256, 0); if (bytes_recv == -1) { //string errorMsg = new System.ComponentModel.Win32Exception(Marshal.GetLastWin32Error()).Message;//Winsock错误获取 int errorno = Marshal.GetLastWin32Error(); if (errorno == 10035) //10035 Socket无数据报错,可能函数原型为异步非阻塞,这里作为阻塞式调用而导致异常,可以忽略 { continue; } MobileDevice.closesocket(from); MobileDevice.closesocket(to); break; } bytes_send = MobileDevice.send(to, recv_buf, bytes_recv, 0); if (bytes_recv == 0 || bytes_recv == -1 || bytes_send == 0 || bytes_send == -1) { MobileDevice.closesocket(from); MobileDevice.closesocket(to); break; } } }
/// <summary> /// 发送消息通过Socket,大部分用途为发送plist文件(指令)给设备 /// </summary> /// <param name="sock"></param> /// <param name="message"></param> /// <returns></returns> public bool SendMessageToSocket(int sock, IntPtr message) { if (sock < 1 || message == IntPtr.Zero) { return(false); } var flag = false; var stream = CoreFoundation.CFWriteStreamCreateWithAllocatedBuffers(IntPtr.Zero, IntPtr.Zero); if (stream != IntPtr.Zero) { if (!CoreFoundation.CFWriteStreamOpen(stream)) { return(false); } var zero = IntPtr.Zero; if (CoreFoundation.CFPropertyListWriteToStream(message, stream, CFPropertyListFormat.kCFPropertyListBinaryFormat_v1_0, ref zero) > 0) { IntPtr srcRef = CoreFoundation.CFWriteStreamCopyProperty(stream, CoreFoundation.kCFStreamPropertyDataWritten); IntPtr buffer = CoreFoundation.CFDataGetBytePtr(srcRef); var bufferlen = CoreFoundation.CFDataGetLength(srcRef); var structure = MobileDevice.htonl((uint)bufferlen); var structureSize = Marshal.SizeOf(structure); if (DeviceSecureIOContext == IntPtr.Zero || SocketContext == IntPtr.Zero) { if (MobileDevice.send_UInt32(sock, ref structure, structureSize, 0) != structureSize) { Console.WriteLine("could not send message size"); } else if (MobileDevice.send(sock, buffer, bufferlen, 0) != bufferlen) { Console.WriteLine("Could not send message."); } else { flag = true; } } else if (MobileDevice.AMDServiceConnectionSend_UInt32(SocketContext, ref structure, structureSize) != structureSize) { Console.WriteLine("could not send message size with socket"); } else if (MobileDevice.AMDServiceConnectionSend(SocketContext, buffer, bufferlen) != bufferlen) { Console.WriteLine("could not send message size"); } else { flag = true; } CoreFoundation.CFRelease(srcRef); } CoreFoundation.CFWriteStreamClose(stream); } return(flag); }