/// <summary> /// This method is just used to make a new connection with NGRID server. /// It receives response of register message and adds communicator to Communicators if successfuly registered. /// </summary> /// <param name="sender">Creator object of event</param> /// <param name="e">Event arguments</param> private void Communicator_MessageReceived(object sender, MessageReceivedFromCommunicatorEventArgs e) { try { //Message must be NGRIDOperationResultMessage var message = e.Message as NGRIDOperationResultMessage; if (message == null) { throw new NGRIDException("First message must be NGRIDOperationResultMessage"); } //Check if remote NGRID server accepted connection if(!message.Success) { throw new NGRIDException("Remote NGRID server did not accept connection."); } //Unregister from event and add communicator to Communicators list. e.Communicator.MessageReceived -= Communicator_MessageReceived; try { AddCommunicator(e.Communicator); } catch (Exception ex) { Logger.Warn(ex.Message, ex); e.Communicator.Stop(false); } } catch (Exception ex) { Logger.Warn("Can not connected to remote NGRID server: '" + Name + "'. Connection is being closed."); Logger.Warn(ex.Message, ex); try { e.Communicator.Stop(false); } catch (Exception ex2) { Logger.Warn(ex2.Message, ex2); } } finally { _reconnectingCommunicator = null; } }
/// <summary> /// Creates a new TCPCommunicator to communicate with NGRID server. /// </summary> private void ConnectToServer() { var ip = IPAddress.Parse(_ipAddress); if (ip == null) { throw new NGRIDException("IP address is not valid: " + _ipAddress); } var socket = GeneralHelper.ConnectToServerWithTimeout(new IPEndPoint(ip, _port), 10000); //10 seconds if (!socket.Connected) { throw new NGRIDException("TCP connection can not be established."); } //Create communicator object. _reconnectingCommunicator = new TCPCommunicator(socket, CommunicationLayer.CreateCommunicatorId()); //Register MessageReceived event to receive response of Register message _reconnectingCommunicator.MessageReceived += Communicator_MessageReceived; //Start communicator and send a register message _reconnectingCommunicator.Start(); _reconnectingCommunicator.SendMessage(new NGRIDRegisterMessage { CommunicationWay = CommunicationWays.SendAndReceive, CommunicatorType = CommunicatorTypes.NgridServer, Name = Settings.ThisServerName, Password = "" //Not implemented yet }); }