当前位置: 首页>>代码示例>>C#>>正文


C# IClient.Connect方法代码示例

本文整理汇总了C#中IClient.Connect方法的典型用法代码示例。如果您正苦于以下问题:C# IClient.Connect方法的具体用法?C# IClient.Connect怎么用?C# IClient.Connect使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在IClient的用法示例。


在下文中一共展示了IClient.Connect方法的8个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的C#代码示例。

示例1: enterButton_Click

 private void enterButton_Click(object sender, EventArgs e)
 {
     _enterForm = new EnterForm();
     if (_enterForm.ShowDialog(this) != DialogResult.OK || Connected)
     {
         return;
     }
     _client = new Client(_enterForm.Name, this, _port, _host);
     _client.Connect();
     Connected = true;
     sendButton.Enabled = true;
     textBox.Enabled = true;
     exitButton.Enabled = true;
     clientsButton.Enabled = true;
     enterButton.Enabled = false;
 }
开发者ID:Veyron154,项目名称:academitCS,代码行数:16,代码来源:ChatForm.cs

示例2: Main

        private static void Main(string[] args)
        {
            string clientName = "Console" + Guid.NewGuid().ToString().Substring(0, 5);

            Log.Default.Logger = new NLogger();
            Log.Default.Initialize(@"D:\TEMP\LOG\", String.Format("TETRINET2_CLIENT_{0}.LOG", clientName));

            IFactory factory = new Factory();

            _client = new Client(factory);
            _client.SetVersion(1, 0);

            ConsoleUI ui = new ConsoleUI(_client);
            IGameController controller = new GameController.GameController(_client);

            //_client.ConnectionLost += OnConnectionLost;

            _client.Connect("net.tcp://localhost:7788/TetriNET2Client", clientName, "team1");

            bool stopped = false;
            while (!stopped)
            {
                if (Console.KeyAvailable)
                {
                    ConsoleKeyInfo cki = Console.ReadKey(true);
                    switch (cki.Key)
                    {
                        default:
                            DisplayHelp();
                            break;
                        case ConsoleKey.O:
                            _client.Connect("net.tcp://localhost:7788/TetriNET2Client", clientName, "team1");
                            break;
                        case ConsoleKey.Z:
                            _client.Disconnect();
                            break;
                        case ConsoleKey.X:
                            _client.Disconnect();
                            stopped = true;
                            break;
                        case ConsoleKey.C:
                            _client.GetClientList();
                            break;
                        case ConsoleKey.G:
                            _client.GetGameList();
                            break;
                        case ConsoleKey.L:
                            _client.GetGameClientList();
                            break;
                        case ConsoleKey.J:
                            _client.CreateAndJoinGame("GAME" + Guid.NewGuid().ToString().Substring(0, 5), null, GameRules.Standard, false);
                            break;
                        case ConsoleKey.R:
                            _client.JoinRandomGame(false);
                            break;
                        case ConsoleKey.S:
                            _client.StartGame();
                            break;
                        case ConsoleKey.T:
                            _client.StopGame();
                            break;

                        // Game controller
                        case ConsoleKey.LeftArrow:
                            controller.KeyDown(Commands.Left);
                            controller.KeyUp(Commands.Left);
                            break;
                        case ConsoleKey.RightArrow:
                            controller.KeyDown(Commands.Right);
                            controller.KeyUp(Commands.Right);
                            break;
                        case ConsoleKey.DownArrow:
                            controller.KeyDown(Commands.Down);
                            controller.KeyUp(Commands.Down);
                            break;
                        case ConsoleKey.H:
                            controller.KeyDown(Commands.Hold);
                            controller.KeyUp(Commands.Hold);
                            break;
                        case ConsoleKey.Spacebar:
                            controller.KeyDown(Commands.Drop);
                            controller.KeyUp(Commands.Drop);
                            break;
                        case ConsoleKey.UpArrow:
                            controller.KeyDown(Commands.RotateClockwise);
                            controller.KeyUp(Commands.RotateClockwise);
                            break;
                        case ConsoleKey.D:
                            controller.KeyDown(Commands.DiscardFirstSpecial);
                            controller.KeyUp(Commands.DiscardFirstSpecial);
                            break;
                        case ConsoleKey.NumPad1:
                        case ConsoleKey.D1:
                            controller.KeyDown(Commands.UseSpecialOn1);
                            controller.KeyUp(Commands.UseSpecialOn1);
                            break;
                        case ConsoleKey.NumPad2:
                        case ConsoleKey.D2:
                            controller.KeyDown(Commands.UseSpecialOn2);
                            controller.KeyUp(Commands.UseSpecialOn2);
//.........这里部分代码省略.........
开发者ID:SinaC,项目名称:TetriNET2,代码行数:101,代码来源:Program.cs

示例3: ServerStart

        /// <summary>
        /// Called when Excel requests the first RTD topic for the server. 
        /// Connect to the broker, returns a on success and 0 otherwise
        /// </summary>
        /// <param name="CallbackObject"></param>
        /// <returns></returns>
        public int ServerStart(IRTDUpdateEvent CallbackObject)
        {
            _onMessage = CallbackObject;  
            string host = "localhost";
            string port = "5673";
            string virtualhost = "test";
            string username = "guest";
            string password = "guest";
            _messageProcessor = getMessage;
          
            if( ConfigurationManager.AppSettings["Host"] != null )
            {
                host = ConfigurationManager.AppSettings["Host"];
            }
            if (ConfigurationManager.AppSettings["Port"] != null)
            {
                port = ConfigurationManager.AppSettings["Port"];
            }
            if (ConfigurationManager.AppSettings["VirtualHost"] != null)
            {
                virtualhost = ConfigurationManager.AppSettings["VirtualHost"];
            }
            if (ConfigurationManager.AppSettings["Username"] != null)
            {
                username = ConfigurationManager.AppSettings["UserName"];
            }
            if (ConfigurationManager.AppSettings["Password"] != null)
            {
                password = ConfigurationManager.AppSettings["Password"];
            }
            if (ConfigurationManager.AppSettings["ProcessorAssembly"] != null)
            {
                try
                {
                    Assembly a = Assembly.LoadFrom(ConfigurationManager.AppSettings["ProcessorAssembly"]);
                    Object o = a.CreateInstance(ConfigurationManager.AppSettings["ProcessorClass"]);
                    MessageProcessor p = (MessageProcessor) o;
                    _messageProcessor = p.ProcessMessage;
                }
                catch (Exception e)
                {
                    System.Windows.Forms.MessageBox.Show("Error: \n" + e.StackTrace);         
                    return 0;
                }
            }

            System.Windows.Forms.MessageBox.Show("Connection parameters: \n host: " + host + "\n port: " 
                                                 + port + "\n user: " + username);
            try
            {
                _client = new Client();            
                _client.Connect(host, Convert.ToInt16(port), virtualhost, username, password);
                // create a session 
                _session = _client.CreateSession(0);          
            }
            catch (Exception e)
            {
                System.Windows.Forms.MessageBox.Show("Error: \n" + e.StackTrace);         
                return 0;
            }
            
            // always successful 
            return 1;
        }
开发者ID:drzo,项目名称:opensim4opencog,代码行数:70,代码来源:ExcelAddIn.cs

示例4: PerfTestClient

 protected PerfTestClient(Options options)
 {
     _options = options;
     _connection = new Client();
     _connection.Connect(options.Broker, options.Port, "test", "guest", "guest");
     _session = _connection.CreateSession(50000);
 }
开发者ID:drzo,项目名称:opensim4opencog,代码行数:7,代码来源:PerfTest.cs

示例5: TryToConnect

		protected void TryToConnect() {
			reqsOutstanding = 1 ;		
			Agent newAgent = new Agent(this,0,"BrokerAgent") ;
			Agents.Add(newAgent.AgentKey(), newAgent) ;
			client = new Client() ;
			client.Connect(url.Hostname, url.Port, null, url.AuthName, url.AuthPassword) ;
			clientSession = client.CreateSession(timeout) ;		
			//clientSession.SetAutoSync(false) ;
			string name = System.Text.Encoding.UTF8.GetString(clientSession.GetName()) ;
			replyName = "reply-" + name ;
			topicName = "topic-" + name ;
			clientSession.SetAutoSync(true) ;
			Option[] options = new Option[] {Option.EXCLUSIVE, Option.AUTO_DELETE} ;
		
			// This queue is used for responses to messages which are sent.	
			clientSession.QueueDeclare(replyName,options) ;
			clientSession.ExchangeBind(replyName,"amq.direct",replyName) ;
			clientSession.AttachMessageListener(this, "rdest") ;			
			clientSession.MessageSubscribe(replyName,"rdest",MessageAcceptMode.NONE,MessageAcquireMode.PRE_ACQUIRED,null,0,null) ;			  			  						
            clientSession.MessageSetFlowMode("rdest", MessageFlowMode.WINDOW);
            clientSession.MessageFlow("rdest", MessageCreditUnit.BYTE, ClientSession.MESSAGE_FLOW_MAX_BYTES);
            clientSession.MessageFlow("rdest", MessageCreditUnit.MESSAGE, ClientSession.MESSAGE_FLOW_MAX_BYTES);  			
		
			// This queue is used for unsolicited messages sent to this class.
			clientSession.QueueDeclare(topicName, options) ;
			clientSession.AttachMessageListener(this, "tdest") ;			
			clientSession.MessageSubscribe(topicName,"tdest",MessageAcceptMode.NONE,MessageAcquireMode.PRE_ACQUIRED,null,0,null) ;							  									
            clientSession.MessageSetFlowMode("tdest", MessageFlowMode.WINDOW);
            clientSession.MessageFlow("tdest", MessageCreditUnit.BYTE, ClientSession.MESSAGE_FLOW_MAX_BYTES);
            clientSession.MessageFlow("tdest", MessageCreditUnit.MESSAGE, ClientSession.MESSAGE_FLOW_MAX_BYTES);  				
			
			outSession = client.CreateSession(timeout) ;	
			outSession.ExchangeBind(replyName,"amq.direct",replyName) ;
			
			connected = true ;
			consoleSession.HandleBrokerConnect(this) ;		
				
			
			IEncoder encoder = CreateEncoder() ;
			this.SetHeader(encoder, 'B', 0) ;
			this.Send(encoder) ;
		}
开发者ID:drzo,项目名称:opensim4opencog,代码行数:42,代码来源:Broker.cs

示例6: InitializeDataChannel

        /// <summary>
        /// Initialize data channel.
        /// </summary>
        /// <param name="settings">Key/value pairs dictionary parsed from connection string.</param>
        protected virtual void InitializeDataChannel(Dictionary<string, string> settings)
        {
            string setting;

            // Instantiate selected transport layer
            switch (m_transportProtocol)
            {
                case TransportProtocol.Tcp:
                    // The TCP transport may be set up as a server or as a client, we distinguish
                    // this simply by deriving the value of an added key/value pair in the
                    // connection string called "IsListener"
                    if (settings.TryGetValue("islistener", out setting))
                    {
                        if (setting.ParseBoolean())
                            m_serverBasedDataChannel = new TcpServer();
                        else
                            m_dataChannel = new TcpClient();
                    }
                    else
                    {
                        // If the key doesn't exist, we assume it's a client connection
                        m_dataChannel = new TcpClient();
                    }
                    break;
                case TransportProtocol.Udp:
                    m_dataChannel = new UdpClient();
                    break;
                case TransportProtocol.Serial:
                    m_dataChannel = new SerialClient();
                    break;
                case TransportProtocol.File:
                    // For file based playback, we allow the option of auto-repeat
                    FileClient fileClient = new FileClient();

                    fileClient.FileAccessMode = FileAccess.Read;
                    fileClient.FileShareMode = FileShare.Read;
                    fileClient.AutoRepeat = m_autoRepeatCapturedPlayback;
                    m_dataChannel = fileClient;
                    break;
                default:
                    throw new InvalidOperationException(string.Format("Transport protocol \"{0}\" is not recognized, failed to initialize data channel", m_transportProtocol));
            }

            // Handle primary data connection, this *must* be defined...
            if (m_dataChannel != null)
            {
                // Setup event handlers
                m_dataChannel.ConnectionEstablished += m_dataChannel_ConnectionEstablished;
                m_dataChannel.ConnectionAttempt += m_dataChannel_ConnectionAttempt;
                m_dataChannel.ConnectionException += m_dataChannel_ConnectionException;
                m_dataChannel.ConnectionTerminated += m_dataChannel_ConnectionTerminated;

                // Attempt connection to device
                m_dataChannel.ReceiveDataHandler = Write;
                m_dataChannel.ReceiveBufferSize = m_bufferSize;
                m_dataChannel.ConnectionString = m_connectionString;
                m_dataChannel.MaxConnectionAttempts = m_maximumConnectionAttempts;
                m_dataChannel.Handshake = false;
                m_dataChannel.Connect();
                m_connectionAttempts = 0;
            }
            else if (m_serverBasedDataChannel != null)
            {
                // Setup event handlers
                m_serverBasedDataChannel.ClientConnected += m_serverBasedDataChannel_ClientConnected;
                m_serverBasedDataChannel.ClientDisconnected += m_serverBasedDataChannel_ClientDisconnected;
                m_serverBasedDataChannel.ServerStarted += m_serverBasedDataChannel_ServerStarted;
                m_serverBasedDataChannel.ServerStopped += m_serverBasedDataChannel_ServerStopped;

                // Listen for device connection
                m_serverBasedDataChannel.ReceiveClientDataHandler = Write;
                m_serverBasedDataChannel.ReceiveBufferSize = m_bufferSize;
                m_serverBasedDataChannel.ConfigurationString = m_connectionString;
                m_serverBasedDataChannel.MaxClientConnections = 1;
                m_serverBasedDataChannel.Handshake = false;
                m_serverBasedDataChannel.Start();
            }
            else
                throw new InvalidOperationException("No data channel was initialized, cannot start frame parser");
        }
开发者ID:avs009,项目名称:gsf,代码行数:84,代码来源:MultiProtocolFrameParser.cs

示例7: InitializeCommandChannel

        /// <summary>
        /// Initialize command channel.
        /// </summary>
        /// <param name="connectionString">Command channel connection string.</param>
        protected virtual void InitializeCommandChannel(string connectionString)
        {
            // Parse command channel connection settings
            Dictionary<string, string> settings = connectionString.ParseKeyValuePairs();

            // Verify user did not attempt to setup command channel as a TCP server
            if (settings.ContainsKey("islistener") && settings["islistener"].ParseBoolean())
                throw new ArgumentException("Command channel cannot be setup as a TCP server.");

            // Validate command channel transport protocol selection
            TransportProtocol transportProtocol = (TransportProtocol)Enum.Parse(typeof(TransportProtocol), settings["protocol"], true);

            if (transportProtocol != TransportProtocol.Tcp && transportProtocol != TransportProtocol.Serial && transportProtocol != TransportProtocol.File)
                throw new ArgumentException("Command channel transport protocol can only be defined as TCP, Serial or File");

            // Instantiate command channel based on defined transport layer
            m_commandChannel = ClientBase.Create(connectionString);

            // Setup event handlers
            m_commandChannel.ConnectionEstablished += m_commandChannel_ConnectionEstablished;
            m_commandChannel.ConnectionAttempt += m_commandChannel_ConnectionAttempt;
            m_commandChannel.ConnectionException += m_commandChannel_ConnectionException;
            m_commandChannel.ConnectionTerminated += m_commandChannel_ConnectionTerminated;

            // Attempt connection to device over command channel
            m_commandChannel.ReceiveDataHandler = Write;
            m_commandChannel.ReceiveBufferSize = m_bufferSize;
            m_commandChannel.MaxConnectionAttempts = m_maximumConnectionAttempts;
            m_commandChannel.Handshake = false;
            m_commandChannel.Connect();
            m_connectionAttempts = 0;
        }
开发者ID:avs009,项目名称:gsf,代码行数:36,代码来源:MultiProtocolFrameParser.cs

示例8: StartProcessing_Click

        private void StartProcessing_Click(object sender, EventArgs e)
        {
            // Validate selection.
            MessagesOutput.Clear();

            if (IDInput.CheckedIndices.Count == 0)
            {
                ShowUpdateMessage("No points selected for processing.");
                return;
            }

            if (!ValidateOutputFormat())
                return;

            // Capture selection.
            DateTime startTime = DateTime.Parse(StartTimeInput.Text, CultureInfo.InvariantCulture.DateTimeFormat);
            DateTime endTime = DateTime.Parse(EndTimeInput.Text, CultureInfo.InvariantCulture.DateTimeFormat);

            try
            {
                StartProcessing.Enabled = false;
                this.Cursor = Cursors.WaitCursor;

                // Dispose previously created client.
                if (m_transmitClient != null)
                    m_transmitClient.Dispose();

                // Create new client.
                ShowUpdateMessage("Initializing client...");

                List<object> state = new List<object>();
                Dictionary<int, Metadata> metadata = new Dictionary<int, Metadata>();

                state.Add(null);
                state.Add(startTime);
                state.Add(endTime);
                state.Add(RepeatDataProcessing.Checked);
                state.Add(OutputPlainTextDataFormat.Text);
                state.Add(int.Parse(ProcessDataAtIntervalSampleRate.Text));
                state.Add(metadata);

                m_transmitStarts = 0;
                m_transmitCompletes = 0;
                m_transmitExceptions = 0;

                switch (OutputChannelTabs.SelectedIndex)
                {
                    case 0: // TCP
                        m_transmitClient = ClientBase.Create(string.Format("Protocol=TCP;Server={0}:{1}", TCPServerInput.Text, TCPPortInput.Text));
                        break;
                    case 1: // UDP
                        m_transmitClient = ClientBase.Create(string.Format("Protocol=UDP;Server={0}:{1};Port=-1", UDPServerInput.Text, UDPPortInput.Text));
                        break;
                    case 2: // File
                        m_transmitClient = ClientBase.Create(string.Format("Protocol=File;File={0}", FileNameInput.Text));
                        if (!AppendToExisting.Checked)
                            (m_transmitClient as FileClient).FileOpenMode = FileMode.Create;
                        break;
                    case 3: // Serial
                        m_transmitClient = ClientBase.Create(string.Format("Protocol=Serial;Port={0};BaudRate={1};Parity={2};StopBits={3};DataBits={4};DtrEnable={5};RtsEnable={6}", SerialPortInput.Text, SerialBaudRateInput.Text, SerialParityInput.Text, SerialStopBitsInput.Text, SerialDataBitsInput.Text, SerialDtrEnable.Checked, SerialRtsEnable.Checked));
                        break;
                }

                m_transmitClient.MaxConnectionAttempts = 10;
                m_transmitClient.SendDataStart += m_transmitClient_SendDataStart;
                m_transmitClient.SendDataComplete += m_transmitClient_SendDataComplete;
                m_transmitClient.SendDataException += m_transmitClient_SendDataException;

                ShowUpdateMessage("Client initialized.");

                // Connect the newly created client.
                ShowUpdateMessage("Connecting client...");

                m_transmitClient.Connect();

                if (m_transmitClient.CurrentState == ClientState.Connected)
                {
                    // Client connected successfully.
                    ShowUpdateMessage("Client connected.");

                    // Queue all selected points for processing.
                    StringBuilder selection = new StringBuilder();
                    Metadata definition = null;

                    for (int i = 0; i < IDInput.CheckedItems.Count; i++)
                    {
                        if (selection.Length > 0)
                            selection.Append(',');

                        definition = (Metadata)IDInput.CheckedItems[i];
                        selection.Append(definition.PointID);
                        metadata.Add(definition.PointID, definition);
                    }

                    state[0] = selection.ToString();

                    if (ProcessDataInParallel.Checked)
                    {
                        ThreadPool.QueueUserWorkItem(Process, state.ToArray());
                    }
//.........这里部分代码省略.........
开发者ID:avs009,项目名称:gsf,代码行数:101,代码来源:Main.cs


注:本文中的IClient.Connect方法示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。