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


C# Socket.Connect方法代码示例

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


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

示例1: Connect

        /// <summary>
        /// Connects to the node debugger.
        /// </summary>
        public void Connect() {
            Socket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
            Socket.NoDelay = true;
            Socket.Connect(new DnsEndPoint(_hostName, _portNumber));

            StartListenerThread();
        }
开发者ID:CforED,项目名称:Node.js-Tools-for-Visual-Studio,代码行数:10,代码来源:NodeConnection.cs

示例2: ConnectIPAddressAny

		public void ConnectIPAddressAny ()
		{
			IPEndPoint ep = new IPEndPoint (IPAddress.Any, 0);

			/* UDP sockets use Any to disconnect
			try {
				using (Socket s = new Socket (AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp)) {
					s.Connect (ep);
					s.Close ();
				}
				Assert.Fail ("#1");
			} catch (SocketException ex) {
				Assert.AreEqual (10049, ex.ErrorCode, "#2");
			}
			*/

			try {
				using (Socket s = new Socket (AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp)) {
					s.Connect (ep);
					s.Close ();
				}
				Assert.Fail ("#3");
			} catch (SocketException ex) {
				Assert.AreEqual (10049, ex.ErrorCode, "#4");
			}
		}
开发者ID:Therzok,项目名称:mono,代码行数:26,代码来源:SocketTest.cs

示例3: Main

        static void Main(string[] args)
        {
            var m_Config = new ServerConfig
            {
                Port = 911,
                Ip = "Any",
                MaxConnectionNumber = 1000,
                Mode = SocketMode.Tcp,
                Name = "CustomProtocolServer"
            };

            var m_Server = new CustomProtocolServer();
            m_Server.Setup(m_Config, logFactory: new ConsoleLogFactory());
            m_Server.Start();

            EndPoint serverAddress = new IPEndPoint(IPAddress.Parse("127.0.0.1"), m_Config.Port);

            using (Socket socket = new Socket(serverAddress.AddressFamily, SocketType.Stream, ProtocolType.Tcp))
            {
                socket.Connect(serverAddress);

                var socketStream = new NetworkStream(socket);
                var reader = new StreamReader(socketStream, Encoding.ASCII, false);

                string charSource = Guid.NewGuid().ToString().Replace("-", string.Empty)
                    + Guid.NewGuid().ToString().Replace("-", string.Empty)
                    + Guid.NewGuid().ToString().Replace("-", string.Empty);

                Random rd = new Random();

                var watch = Stopwatch.StartNew();
                for (int i = 0; i < 10; i++)
                {
                    int startPos = rd.Next(0, charSource.Length - 2);
                    int endPos = rd.Next(startPos + 1, charSource.Length - 1);

                    var currentMessage = charSource.Substring(startPos, endPos - startPos + 1);

                    byte[] requestNameData = Encoding.ASCII.GetBytes("ECHO");
                    socketStream.Write(requestNameData, 0, requestNameData.Length);
                    var data = Encoding.ASCII.GetBytes(currentMessage);
                    socketStream.Write(new byte[] { (byte)(data.Length / 256), (byte)(data.Length % 256) }, 0, 2);
                    socketStream.Write(data, 0, data.Length);
                    socketStream.Flush();

                   // Console.WriteLine("Sent: " + currentMessage);

                    var line = reader.ReadLine();
                    //Console.WriteLine("Received: " + line);
                    //Assert.AreEqual(currentMessage, line);
                }

                

                watch.Stop();
                Console.WriteLine(watch.ElapsedMilliseconds);
            }

            Console.ReadLine();
        }
开发者ID:zesus19,项目名称:c5.v1,代码行数:60,代码来源:Program.cs

示例4: Main

 public static void Main()
 {
     using (Socket clientSocket = new Socket(AddressFamily.InterNetwork,
                                             SocketType.Stream,
                                             ProtocolType.Tcp))
     {
         // Addressing
         IPAddress ipAddress = IPAddress.Parse(dottedServerIPAddress);
         IPEndPoint serverEndPoint = new IPEndPoint(ipAddress, port);
         // Connecting
         Debug.Print("Connecting to server " + serverEndPoint + ".");
         clientSocket.Connect(serverEndPoint);
         Debug.Print("Connected to server.");
         using (SslStream sslStream = new SslStream(clientSocket))
         {
             X509Certificate rootCA =
                      new X509Certificate(Resources.GetBytes(Resources.BinaryResources.MyRootCA));
             X509Certificate clientCert =
                      new X509Certificate(Resources.GetBytes(Resources.BinaryResources.MyRootCA));
             sslStream.AuthenticateAsClient("MyServerName", // Hostname needs to match CN of server cert
                                            clientCert, // Authenticate client
                                            new X509Certificate[] { rootCA }, // CA certs for verification
                                            SslVerification.CertificateRequired, // Verify server
                                            SslProtocols.Default // Protocols that may be required
                                            );
             // Sending
             byte[] messageBytes = Encoding.UTF8.GetBytes("Hello World!");
             sslStream.Write(messageBytes, 0, messageBytes.Length);
         }
     }// the socket will be closed here
 }
开发者ID:brandongrossutti,项目名称:DotCopter,代码行数:31,代码来源:Program.cs

示例5: Main

        static void Main(string[] args)
        {
            byte[] receiveBytes = new byte[1024];
            int port =8080;//服务器端口
            string host = "10.3.0.1";  //服务器ip
            
            IPAddress ip = IPAddress.Parse(host);
            IPEndPoint ipe = new IPEndPoint(ip, port);//把ip和端口转化为IPEndPoint实例 
            Console.WriteLine("Starting Creating Socket Object");
            Socket sender = new Socket(AddressFamily.InterNetwork, 
                                        SocketType.Stream, 
                                        ProtocolType.Tcp);//创建一个Socket 
            sender.Connect(ipe);//连接到服务器 
            string sendingMessage = "Hello World!";
            byte[] forwardingMessage = Encoding.ASCII.GetBytes(sendingMessage + "[FINAL]");
            sender.Send(forwardingMessage);
            int totalBytesReceived = sender.Receive(receiveBytes);
            Console.WriteLine("Message provided from server: {0}",
                              Encoding.ASCII.GetString(receiveBytes,0,totalBytesReceived));
            //byte[] bs = Encoding.ASCII.GetBytes(sendStr);

            sender.Shutdown(SocketShutdown.Both);  
            sender.Close();
            Console.ReadLine();
        }
开发者ID:qychen,项目名称:AprvSys,代码行数:25,代码来源:ClientCode.cs

示例6: ToConnectObservable

        public static IObservable<Socket> ToConnectObservable(this IPEndPoint endpoint, Selector selector, CancellationToken token)
        {
            return Observable.Create<Socket>(observer =>
            {
                var socket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp) { Blocking = false };

                Exception error = null;
                bool isConnected = false;

                try
                {
                    socket.Connect(endpoint);
                    isConnected = true;
                }
                catch (Exception exception)
                {
                    if (!exception.IsWouldBlock())
                        error = exception;
                }
                if (!isConnected && error == null)
                {
                    var waitEvent = new ManualResetEvent(false);
                    var waitHandles = new[] {token.WaitHandle, waitEvent};

                    selector.AddCallback(SelectMode.SelectWrite, socket,
                        _ =>
                        {
                            try
                            {
                                if (!socket.Connected)
                                    socket.Connect(endpoint);
                                selector.RemoveCallback(SelectMode.SelectWrite, socket);
                                isConnected = true;
                                waitEvent.Set();
                            }
                            catch (Exception exception)
                            {
                                if (exception.IsWouldBlock())
                                    return;
                                error = exception;
                                waitEvent.Set();
                            }
                        });

                    if (WaitHandle.WaitAny(waitHandles) == 0)
                        token.ThrowIfCancellationRequested();
                }

                if (error == null)
                    observer.OnNext(socket);
                else
                    observer.OnError(error);

                observer.OnCompleted();

                return Disposable.Empty;
            });
        }
开发者ID:tleviathan,项目名称:JetBlack.Network,代码行数:58,代码来源:ConnectExtensions.cs

示例7: connect

 public override void connect()
 {
     _socket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
     IPAddress ip = null;
     if (IPAddress.TryParse(DataSource.Provider, out ip))
     {
         _socket.Connect(ip, DataSource.Port);
     }
     else
     {
         _socket.Connect(DataSource.Provider, DataSource.Port);
     }
 }
开发者ID:ChristopherEdwards,项目名称:mdo,代码行数:13,代码来源:SocketConnection.cs

示例8: cancelIO

        protected override void cancelIO() 
        { 
            try 
            { 
                Socket s = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
#if NET_FRAMEWORK_20
                s.Connect(new IPEndPoint(Dns.GetHostEntry("localhost").AddressList[0], port));	
#else
                s.Connect(new IPEndPoint(Dns.Resolve("localhost").AddressList[0], port));	
#endif
                s.Close();
            } 
            catch (SocketException) {}
        }
开发者ID:yan122725529,项目名称:TripRobot.Crawler,代码行数:14,代码来源:ReplicationStaticSlaveStorageImpl.cs

示例9: PostStream

	static string PostStream (Mono.Security.Protocol.Tls.SecurityProtocolType protocol, string url, byte[] buffer)
	{
		Uri uri = new Uri (url);
		string post = "POST " + uri.AbsolutePath + " HTTP/1.0\r\n";
		post += "Content-Type: application/x-www-form-urlencoded\r\n";
		post += "Content-Length: " + (buffer.Length + 5).ToString () + "\r\n";
		post += "Host: " + uri.Host + "\r\n\r\n";
		post += "TEST=";
		byte[] bytes = Encoding.Default.GetBytes (post);

		IPHostEntry host = Dns.Resolve (uri.Host);
		IPAddress ip = host.AddressList [0];
		Socket socket = new Socket (ip.AddressFamily, SocketType.Stream, ProtocolType.Tcp);
		socket.Connect (new IPEndPoint (ip, uri.Port));
		NetworkStream ns = new NetworkStream (socket, false);
		SslClientStream ssl = new SslClientStream (ns, uri.Host, false, protocol);
		ssl.ServerCertValidationDelegate += new CertificateValidationCallback (CertificateValidation);

		ssl.Write (bytes, 0, bytes.Length);
		ssl.Write (buffer, 0, buffer.Length);
		ssl.Flush ();

		StreamReader reader = new StreamReader (ssl, Encoding.UTF8);
		string result = reader.ReadToEnd ();
		int start = result.IndexOf ("\r\n\r\n") + 4;
		start = result.IndexOf ("\r\n\r\n") + 4;
		return result.Substring (start);
	}
开发者ID:Jakosa,项目名称:MonoLibraries,代码行数:28,代码来源:postecho.cs

示例10: Main

        static void Main(string[] args)
        {
            //TODO: 1. Utworzenie punktu połączenia do serwera - IPEndPoint
            var punktSerwer = new IPEndPoint(IPAddress.Parse("192.168.1.163"), 2000);
            //TODO: 2. Utworzenie gniazda połączenia - Socket
            var gniazdoSerwer = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
            //TODO: 3. Połączenie z serwerem - Socket.Connect
            gniazdoSerwer.Connect(punktSerwer); //połączenie z serwerem
            //TODO: 4. Pobranie danych z serwera - Socket.Receive(ASCIIEncoding)       
            var tablicaDane = new byte[64]; //Bajt
            gniazdoSerwer.Receive(tablicaDane);  //Oczekiwanie i pobranie danych
            Console.WriteLine(Encoding.UTF8.GetString(tablicaDane));

            var watek = new Thread(WysylanieCzat); //wątek dla nadłuchiwania z klawiatury i wysyłania do serwera
            watek.IsBackground = true;
            watek.Start(gniazdoSerwer);

            while (true) //pętla dla obierania wiadomości
            {
                var dane = new byte[512]; //256 -> 3 znaki + 253 spacje
                gniazdoSerwer.Receive(dane);
                Console.WriteLine(Encoding.UTF8.GetString(dane));
            }
            //Kod - klient równocześnie wysyła i odbiera komunikaty           
        }
开发者ID:mozajik,项目名称:web_calc,代码行数:25,代码来源:Program.cs

示例11: ConnectToServerWithTimeout

        /// <summary>
        /// This code is used to connect to a TCP socket with timeout option.
        /// </summary>
        /// <param name="endPoint">IP endpoint of remote server</param>
        /// <param name="timeoutMs">Timeout to wait until connect</param>
        /// <returns>Socket object connected to server</returns>
        public static Socket ConnectToServerWithTimeout(EndPoint endPoint, int timeoutMs)
        {
            var socket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
            try
            {
                socket.Blocking = false;
                socket.Connect(endPoint);
                socket.Blocking = true;
                return socket;
            }
            catch (SocketException socketException)
            {
                if (socketException.ErrorCode != 10035)
                {
                    socket.Close();
                    throw;
                }

                if (!socket.Poll(timeoutMs * 1000, SelectMode.SelectWrite))
                {
                    socket.Close();
                    throw new NGRIDException("The host failed to connect. Timeout occured.");
                }

                socket.Blocking = true;
                return socket;
            }
        }
开发者ID:ashwinrath,项目名称:NGRID,代码行数:34,代码来源:GeneralHelper.cs

示例12: TestSwitcher

        public void TestSwitcher()
        {
            EndPoint serverAddress = new IPEndPoint(IPAddress.Parse("127.0.0.1"), m_Config.Port);

            Random rd = new Random();

            using (Socket socket = new Socket(serverAddress.AddressFamily, SocketType.Stream, ProtocolType.Tcp))
            {
                socket.Connect(serverAddress);

                for (int i = 0; i < 100; i++)
                {
                    var line = Guid.NewGuid().ToString();
                    var commandLine = "ECHO " + line;

                    var data = new byte[line.Length + 3 + 5];
                    var len = 0;

                    if (rd.Next(0, 100) / 2 == 0)
                    {
                        data[0] = (byte)'*';
                        len = Encoding.ASCII.GetBytes(commandLine, 0, commandLine.Length, data, 1);
                        data[len + 1] = (byte)'#';
                        len += 2;
                    }
                    else
                    {
                        data[0] = (byte)'Y';
                        len = Encoding.ASCII.GetBytes(commandLine, 0, commandLine.Length, data, 1);
                        data[len + 1] = 0x00;
                        data[len + 2] = 0xff;
                        len += 3;
                    }

                    socket.Send(data, 0, len, SocketFlags.None);

                    var task = Task.Factory.StartNew<string>(() =>
                        {
                            byte[] response = new byte[line.Length + 2]; //2 for \r\n

                            int read = 0;

                            while (read < response.Length)
                            {
                                read += socket.Receive(response, read, response.Length - read, SocketFlags.None);
                            }

                            return Encoding.ASCII.GetString(response, 0, response.Length - 2);//trim \r\n
                        });

                    if (!task.Wait(2000))
                    {
                        Assert.Fail("Timeout");
                        return;
                    }

                    Assert.AreEqual(line, task.Result);
                }
            }
        }
开发者ID:RocChing,项目名称:SuperSocket,代码行数:60,代码来源:Test.cs

示例13: nhapDL

 private void nhapDL()
 {
     Socket s = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
     IPEndPoint ie = new IPEndPoint(IPAddress.Parse("127.0.0.1"), 9000);
     s.Connect(ie);
     while (true)
     {
         MessageBox.Show("Connected to Server.....");
         byte[] data = new byte[1024];
         int k1 = s.Receive(data);
         string A = txtNumber1.Text;
         string B = txtNumber2.Text;
         string gep = string.Concat(A, "-", B).Trim();
         data = Encoding.ASCII.GetBytes(gep);
         s.Send(data, data.Length, SocketFlags.None);
         data = new byte[1024];
         int k = s.Receive(data);
         txtKQ.Text += Encoding.ASCII.GetString(data, 0, k);
         if (Convert.ToInt32(txtNumber1.Text)==0 && Convert.ToInt32(txtNumber2.Text)==0)
         {
             MessageBox.Show("End connect...");
             break;
         }
     }
 }
开发者ID:pthdnq,项目名称:csharp-project-nduang,代码行数:25,代码来源:Form1.cs

示例14: GetDomain

        /// <summary>
        /// 域名注册信息
        /// </summary>
        /// <param name="domain">输入域名,不包含www</param>
        /// <returns></returns>
        public static string GetDomain(string domain) {
            string strServer;
            string whoisServer = "whois.internic.net,whois.cnnic.net.cn,whois.publicinterestregistry.net,whois.nic.gov,whois.hkdnr.net.hk,whois.nic.name";
            string[] whoisServerList = Regex.Split(whoisServer, ",", RegexOptions.IgnoreCase);

            if (domain == null)
                throw new ArgumentNullException();
            int ccStart = domain.LastIndexOf(".");
            if (ccStart < 0 || ccStart == domain.Length)
                throw new ArgumentException();

            //根据域名后缀选择服务器
            string domainEnd = domain.Substring(ccStart + 1).ToLower();
            switch (domainEnd) {
                default:    //.COM, .NET, .EDU 
                    strServer = whoisServerList[0];
                    break;
                case "cn":  //所有.cn的域名
                    strServer = whoisServerList[1];
                    break;
                case "org":  //所有.org的域名
                    strServer = whoisServerList[2];
                    break;
                case "gov":  //所有.gov的域名
                    strServer = whoisServerList[3];
                    break;
                case "hk":  //所有.hk的域名
                    strServer = whoisServerList[4];
                    break;
                case "name":  //所有.name的域名
                    strServer = whoisServerList[5];
                    break;
            }

            string ret = "";
            Socket s = null;
            try {
                string cc = domain.Substring(ccStart + 1);
                s = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
                s.SendTimeout = 900;
                s.Connect(new IPEndPoint(Dns.Resolve(strServer).AddressList[0], 43));
                s.Send(Encoding.ASCII.GetBytes(domain + "\r\n"));
                byte[] buffer = new byte[1024];
                int recv = s.Receive(buffer);
                while (recv > 0) {
                    ret += Encoding.UTF8.GetString(buffer, 0, recv);
                    recv = s.Receive(buffer);
                }
                s.Shutdown(SocketShutdown.Both);


            } catch (SocketException ex) {
                return ex.Message;
            } finally {
                if (s != null)
                    s.Close();
            }

            return ret;
        }
开发者ID:qcjxberin,项目名称:SmartSpider,代码行数:65,代码来源:WhoisSearch.cs

示例15: ModbusTcpInterface

 /// <summary>
 /// Creates a new Modbus TCP interface. This will connect to a TCP server listening to the given port.
 /// This interface can be used with <see cref="ModbusMaster"/>.
 /// </summary>
 /// <param name="host">Host name or ip address of the Modbus TCP device.</param>
 /// <param name="port">Port to which the devuice is listening. The Modbus TCP default port is 502.</param>
 /// <param name="maxDataLength">Maximum allowed length of function code specific data.</param>
 public ModbusTcpInterface(string host, int port = 502, short maxDataLength = 252)
 {
    IPAddress ip;
    try
    {
       ip = IPAddress.Parse(host);
    }
    catch
    {
       ip = Dns.GetHostEntry(host).AddressList[0];
    }
    _Socket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
    try
    {
       _Socket.Connect(new IPEndPoint(ip, port));
       _OwnsSocket = true;
    }
    catch
    {
       _Socket = null;
       _OwnsSocket = false;
       throw;
    }
    MaxDataLength = maxDataLength;
    MaxTelegramLength = (short)(maxDataLength + 8);
 }
开发者ID:gremlinc5,项目名称:ModbusLib,代码行数:33,代码来源:ModbusTcpInterface.cs


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