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


C# TcpClient.Connect方法代码示例

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


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

示例1: TryConnect

    //пытаемся отправить кому-то сообщение о том, что хотим понаблюдать за его игрой
    //если прокатывает - в ответ нам начнут приходить сообщения о состоянии игры
    public void TryConnect(string ip, string port)
    {
        try
        {
            TcpClient tcpclnt = new TcpClient();
            tcpclnt.Connect(IPAddress.Parse(ip), int.Parse(port));
            String str = Dns.GetHostByName(Dns.GetHostName()).AddressList[0].ToString();
            Stream stm = tcpclnt.GetStream();

            ASCIIEncoding asen = new ASCIIEncoding();
            byte[] ba = asen.GetBytes(str);
            stm.Write(ba, 0, ba.Length);
            byte[] bb = new byte[255];
            int k = stm.Read(bb, 0, 255);

            string an = "";
            for (int i = 0; i < k; i++)
                an += Convert.ToChar(bb[i]);

            stm.Close();
            tcpclnt.Close();
        }
        catch (Exception e)
        {
            Debug.LogError(e.StackTrace);
        }
    }
开发者ID:BoogieGo,项目名称:avegames_task,代码行数:29,代码来源:NetworkManager.cs

示例2: button1_Click

        private void button1_Click(object sender, EventArgs e)
        {
            try
            {
                //создание экземпляра класса IPEndPoint
                IPEndPoint endPoint = new IPEndPoint(
                    IPAddress.Parse(textBox1.Text),
                    Convert.ToInt32(textBox3.Text)
                );
                client = new TcpClient();
                //установка соединения с использованием 
                //данных IP и номера порта
                client.Connect(endPoint);

                //получение сетевого потока
                NetworkStream nstream = client.GetStream();
                //преобразование строки сообщения в массив байт
                byte[] barray = Encoding.Unicode.GetBytes(textBox2.Text);
                //запись в сетевой поток всего массива 
                nstream.Write(barray, 0, barray.Length);
                //закрытие клиента
                client.Close();
            }
            catch (SocketException sockEx)
            {
                MessageBox.Show("Ошибка сокета:" + sockEx.Message);
            }
            catch (Exception Ex)
            {
                MessageBox.Show("Ошибка :" + Ex.Message);
            }
        }
开发者ID:xs2ranjeet,项目名称:13ns9-1spr,代码行数:32,代码来源:Form1.cs

示例3: Main

        public static void Main()
        {
            while (true)
            {

                try
                {
                    IP = null;
                    Application.Run(new InputIp());
                    tcpclnt = new TcpClient();
                    if (IP == null)
                        return;
                    Console.WriteLine(IP);
                    tcpclnt.Connect(IP, 8001);
                    Console.WriteLine("Connection established");
                    gui = new MinesweeperGUI();
                    Application.Run(gui);
                    break;
                }
                catch (Exception e)
                {
                    MessageBox.Show("Could not establish a connection with the server: " + e.Message);
                }
            }
        }
开发者ID:ICanHaz,项目名称:Visual-C-,代码行数:25,代码来源:Client.cs

示例4: Initialize

    public static bool Initialize(string ip)
    {
        bool connection_failure = false;

        if(client != null)
        {
            receive_thread.Abort();
            send_thread.Abort();
            sreader.Close();
            swriter.Close();

        }

        client = new TcpClient();
        client.Connect(ip, port);
        var stream = client.GetStream();

        swriter = new StreamWriter(stream);
        sreader = new StreamReader(stream);

        receive_thread = new Thread(new ThreadStart(Receiver));
        receive_thread.Start();

        send_thread = new Thread(new ThreadStart(Sender));
        send_thread.Start();

        return connection_failure;
    }
开发者ID:JessicaMaxey,项目名称:Networks,代码行数:28,代码来源:NetworkController.cs

示例5: loginButton_Click

        private void loginButton_Click(object sender, EventArgs e)
        {
            if (!ValidLoginInput())
                return;

            try {
                TcpClient client = new TcpClient();
                client.Connect(ipAddress, port);
                Connection conn = new Connection(client, true);

                conn.SendData(new AuthenticationRequest(GetUsername(), GetPassword()));

                AuthenticationResponse authentication = (AuthenticationResponse)conn.ReceiveData();

                if (authentication.Message == null) {
                    ConnectionsRepository.AddConnection(conn, true);
                    conn.DataTransfered += DataProcessor.ProcessData;
                    conn.InitializeDataListener();

                    this.Visible = false;
                    this.ShowInTaskbar = false;

                    GameForm game = new GameForm(conn);
                    conn.ShutdownRequest += ServerDown;
                    game.FormClosed += CloseClient;
                    game.Show();
                } else
                    noteLabel.Text = authentication.Message;

            } catch {
                noteLabel.Text = "No response from server.";
            }
        }
开发者ID:randqm,项目名称:Csharp_client-server_framework,代码行数:33,代码来源:Authentication.cs

示例6: SSLAuthenticateTest

    void SSLAuthenticateTest()
    {
        var client = new TcpClient ();
        String hosturl = "115.239.211.112";//www.baidu.com;
        client.Connect (hosturl, 443);

        using (var stream = client.GetStream ())
        {
            Debug.Log("CONNECTING ");
            var ostream = stream as Stream;
            if (true)
            {
                ostream = new SslStream (stream, false, new RemoteCertificateValidationCallback (ValidateServerCertificate));

                try
                {
                    var ssl = ostream as SslStream;
                    ssl.AuthenticateAsClient (hosturl);
                }
                catch (Exception e)
                {
                    Debug.Log ("Exception: " + e.Message);
                }
            }
        }
    }
开发者ID:xfanhsl,项目名称:IL2CPP_Test,代码行数:26,代码来源:IL2CPPCompatible.cs

示例7: Connect

 public void Connect()
 {
     listener = new TcpClient ();
     listener.Connect (ip, porta);
     client = listener.GetStream();
     print ("Connected");
 }
开发者ID:Survivers,项目名称:Andreduino,代码行数:7,代码来源:conexaoTCP.cs

示例8: ThreadListener

    private void ThreadListener()
    {
        client = new TcpClient();
        try
        {
            client.Connect(host, port);
            ns = client.GetStream();

            write("READY");

            running = true;
            while (running)
            {
                threadUpdate();
            }
        }
        catch (SocketException e)
        {
            Debug.LogException(e, this);
            if (!running)
            {
                //tenta conectar novamente
                ThreadListener();
            }
            else
            {
                GameController.gameState = GameController.GameState.EXIT;
            }
        }
    }
开发者ID:valdenio,项目名称:BatalhaDoUniverso,代码行数:30,代码来源:GameSocketConnectionThread.cs

示例9: ConnectWithV4AndV6_Success

        public void ConnectWithV4AndV6_Success()
        {
            TcpListener listener = TcpListener.Create(TestPortBase + 3);
            listener.Start();
            IAsyncResult asyncResult = listener.BeginAcceptTcpClient(null, null);

            TcpClient v6Client = new TcpClient(AddressFamily.InterNetworkV6);
            v6Client.Connect(new IPEndPoint(IPAddress.IPv6Loopback, TestPortBase + 3));

            TcpClient acceptedV6Client = listener.EndAcceptTcpClient(asyncResult);
            Assert.Equal(AddressFamily.InterNetworkV6, acceptedV6Client.Client.RemoteEndPoint.AddressFamily);
            Assert.Equal(AddressFamily.InterNetworkV6, v6Client.Client.RemoteEndPoint.AddressFamily);

            asyncResult = listener.BeginAcceptTcpClient(null, null);

            TcpClient v4Client = new TcpClient(AddressFamily.InterNetwork);
            v4Client.Connect(new IPEndPoint(IPAddress.Loopback, TestPortBase + 3));

            TcpClient acceptedV4Client = listener.EndAcceptTcpClient(asyncResult);
            Assert.Equal(AddressFamily.InterNetworkV6, acceptedV4Client.Client.RemoteEndPoint.AddressFamily);
            Assert.Equal(AddressFamily.InterNetwork, v4Client.Client.RemoteEndPoint.AddressFamily);
            
            v6Client.Dispose();
            acceptedV6Client.Dispose();

            v4Client.Dispose();
            acceptedV4Client.Dispose();

            listener.Stop();
        }
开发者ID:hitomi333,项目名称:corefx,代码行数:30,代码来源:AgnosticListenerTest.cs

示例10: ConnectToServer

	public void ConnectToServer( string ip, ushort port)
	{
		if( ( null != m_socket_integrated) && ( true == m_socket_integrated.Connected))
			InitSocket();

		m_socket_integrated = new TcpClient();

		try
		{
			m_socket_integrated.Connect( ip, port);
		}
		catch( Exception e)
		{
			Debug.Log( "Exception : " + e);
			throw;
		}

		if( true == m_socket_integrated.Connected)
		{
			isConnected = m_socket_integrated.Connected;
			
			m_socket_game = AsNetworkManager.Instance.Socket;
			AsNetworkManager.Instance.SwitchServer( m_socket_integrated);
		}
	}
开发者ID:ftcaicai,项目名称:ArkClient,代码行数:25,代码来源:AsNetworkIntegratedManager.cs

示例11: connectStatus

 public static bool connectStatus(TcpClient tcpclnt, string iPAddress, int portNumber)
 {
     IPAddress ipAdd = IPAddress.Any;
     tcpclnt.Connect(iPAddress, portNumber);
     bool connectedStatus = tcpclnt.Connected;
     return connectedStatus;
 }
开发者ID:ribler,项目名称:CS-Connection,代码行数:7,代码来源:Client.cs

示例12: ConnectWithV4AndV6_Success

        public void ConnectWithV4AndV6_Success()
        {
            int port;
            TcpListener listener = SocketTestExtensions.CreateAndStartTcpListenerOnAnonymousPort(out port);
            IAsyncResult asyncResult = listener.BeginAcceptTcpClient(null, null);

            TcpClient v6Client = new TcpClient(AddressFamily.InterNetworkV6);
            v6Client.Connect(new IPEndPoint(IPAddress.IPv6Loopback, port));

            TcpClient acceptedV6Client = listener.EndAcceptTcpClient(asyncResult);
            Assert.Equal(AddressFamily.InterNetworkV6, acceptedV6Client.Client.RemoteEndPoint.AddressFamily);
            Assert.Equal(AddressFamily.InterNetworkV6, v6Client.Client.RemoteEndPoint.AddressFamily);

            asyncResult = listener.BeginAcceptTcpClient(null, null);

            TcpClient v4Client = new TcpClient(AddressFamily.InterNetwork);
            v4Client.Connect(new IPEndPoint(IPAddress.Loopback, port));

            TcpClient acceptedV4Client = listener.EndAcceptTcpClient(asyncResult);
            Assert.Equal(AddressFamily.InterNetworkV6, acceptedV4Client.Client.RemoteEndPoint.AddressFamily);
            Assert.Equal(AddressFamily.InterNetwork, v4Client.Client.RemoteEndPoint.AddressFamily);

            v6Client.Dispose();
            acceptedV6Client.Dispose();

            v4Client.Dispose();
            acceptedV4Client.Dispose();

            listener.Stop();
        }
开发者ID:rainersigwald,项目名称:corefx,代码行数:30,代码来源:AgnosticListenerTest.cs

示例13: LookingForServer

	void LookingForServer()		
	{
		while(mConnected == false)
		{
			Thread.Sleep(500);
			try {
				TcpClient tcpclnt = new TcpClient();
				Debug.Log("Connecting.....");
				
				//tcpclnt.Connect("192.168.13.113",8001);
				tcpclnt.Connect(Config.ip,8001);
				// use the ipaddress as in the server program
				mConnected =true;
				
				mServerStream = tcpclnt.GetStream();
				
				ThreadStart ts = new ThreadStart(ListenServer);		
				mThreadListen = new Thread(ts);		
				mThreadListen.Start();
			}
			
			catch (Exception e) {
				Debug.Log("Error..... " + e.StackTrace);
			}
		}
		mSynchronizing = false;
	}
开发者ID:proudaut,项目名称:GGJ,代码行数:27,代码来源:SocketClient.cs

示例14: Main

        static void Main(string[] args)
        {
            Console.Write("IP: ");
            IPAddress ip = IPAddress.Parse(Console.ReadLine());
            Console.Write("Slóð: ");
            string slod = Console.ReadLine();

            try
            {
                TcpClient client = new TcpClient();
                client.Connect(new IPEndPoint(ip, 1337));
                NetworkStream s = client.GetStream();

                StreamWriter sw = new StreamWriter(s);
                sw.WriteLine(slod);
                sw.Flush();

                StreamReader sr = new StreamReader(s);
                Console.WriteLine(sr.ReadLine());

                s.Close();
                client.Close();
            }
            catch (Exception e)
            {
                Console.WriteLine("Villa!");
                Console.WriteLine(e.Message);
                Console.WriteLine(e.StackTrace);
            }

            Console.ReadLine();
        }
开发者ID:SuprDewd,项目名称:Forritunarkeppnin-2,代码行数:32,代码来源:Program.cs

示例15: ConnectToServer

    /// <summary>
    /// 連線至主機
    /// </summary>
    public void ConnectToServer()
    {
        //先建立IPAddress物件,IP為欲連線主機之IP
        IPAddress ipa = IPAddress.Parse(ConnectManager.ServerIP);

        //建立IPEndPoint
        IPEndPoint ipe = new IPEndPoint(ipa, ConnectManager.Port);

        //先建立一個TcpClient;
        TcpClient tcpClient = new TcpClient();

        //開始連線
        try
        {
            Debug.Log("主機IP=(" + ipa.ToString() + ") Port(" + ConnectManager.Port + ")");
            Debug.Log("客戶端連線至主機中...\n");
            tcpClient.Connect(ipe);
            if (tcpClient.Connected)
            {
                Debug.Log("客服端連線成功!");
                CommunicationBase cb = new CommunicationBase();
                cb.SendMsg("這是客戶端傳給主機的訊息", tcpClient);
                Debug.Log(cb.ReceiveMsg(tcpClient));
            }
            else
            {
                Debug.Log("客服端連線失敗!");
            }
        }
        catch (System.Exception ex)
        {
            tcpClient.Close();
            Debug.Log(ex.Message);
        }
    }
开发者ID:gmfnasg,项目名称:UnitySocket,代码行数:38,代码来源:Client.cs


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