private Socket Connect(IPAddress ipAddress, ConnectCommandBase connectCmd, int sendTimeout) { Socket socket = null; try { socket = new Socket(ipAddress.AddressFamily, SocketType.Stream, ProtocolType.IP); if (sendTimeout > 0) { socket.SendTimeout = sendTimeout; } var endpoint = new IPEndPoint(ipAddress, Sdk.IkusNet.ExternalProtocolIpCommandsPort); socket.Connect(endpoint, TimeSpan.FromMilliseconds(1000)); if (!socket.Connected) { socket.Close(); return(null); } var sent = SendCommand(socket, connectCmd); if (sent <= 0 || !socket.Connected) { socket.Close(); return(null); } var ackResponse = new AcknowledgeResponse(socket); log.Debug("Connect response from codec at {0}: {1}", ipAddress, ackResponse); var success = ackResponse.Acknowleged; if (!success) { socket.Close(); return(null); } return(socket); } catch (Exception ex) { log.Warn(ex, "Exception when connecting to codec at {0}", ipAddress); socket?.Close(); return(null); } }
private static async Task <ProdysSocket> ConnectAsync(IPAddress ipAddress, ConnectCommandBase connectCmd, int sendTimeout) { ProdysSocket socket = null; try { socket = new ProdysSocket(ipAddress); if (sendTimeout > 0) { socket.SendTimeout = sendTimeout; } var endpoint = new IPEndPoint(ipAddress, Sdk.IkusNet.ExternalProtocolIpCommandsPort); await socket.ConnectAsync(endpoint, 4000); // TODO: Added a timeout here, verify that it's ok if (!socket.Connected) { socket.Close(); return(null); } var sendBytes = connectCmd.GetBytes(); var sent = socket.Send(sendBytes); if (sent <= 0 || !socket.Connected) { socket.Close(); return(null); } // Read response var buffer = new byte[16]; socket.Receive(buffer); var command = (Command)ConvertHelper.DecodeUInt(buffer, 0); var length = (int)ConvertHelper.DecodeUInt(buffer, 4); var receivedCommand = (Command)ConvertHelper.DecodeUInt(buffer, 8); // TODO: Verify command, length, receivedCommand var acknowledged = Convert.ToBoolean(ConvertHelper.DecodeUInt(buffer, 12)); log.Debug("Connect response from codec at {0}: {1}", ipAddress, acknowledged); if (!acknowledged) { socket.Close(); socket.Dispose(); return(null); } return(socket); } catch (Exception ex) { log.Warn(ex, $"Exception when connecting to codec at {ipAddress}, {ex.GetType().FullName}"); log.Debug(ex, "Exception when using Prodys socket"); socket?.Close(); return(null); } }