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


C# Net.IPEndPoint类代码示例

本文整理汇总了C#中System.Net.IPEndPoint的典型用法代码示例。如果您正苦于以下问题:C# IPEndPoint类的具体用法?C# IPEndPoint怎么用?C# IPEndPoint使用的例子?那么恭喜您, 这里精选的类代码示例或许可以为您提供帮助。


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

示例1: button1_Click

        private void button1_Click(object sender, EventArgs e)
        {
            System.Diagnostics.Stopwatch watch = new System.Diagnostics.Stopwatch();
            var ControllerIPAddress = new IPAddress(new byte[] { 192, 168, 0, 2 });
            var ControllerPort = 40001;
            var ControllerEndPoint = new IPEndPoint(ControllerIPAddress, ControllerPort);
            _client = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);

            var header = "@";
            var command = "00C";
            var checksum = "E3";
            var end = "\r\n";
            var data = header + command + checksum + end;
            byte[] bytes = new byte[1024];

            //Start Connect
            _connectDone.Reset();
            watch.Start();
            _client.BeginConnect(ControllerIPAddress, ControllerPort, new AsyncCallback(ConnectCallback), _client);
            //wait 2s
            _connectDone.WaitOne(2000, false);

            var text = (_client.Connected) ? "ok" : "ng";
            richTextBox1.AppendText(text + "\r\n");
            watch.Stop();
            richTextBox1.AppendText("Consumer time: " + watch.ElapsedMilliseconds + "\r\n");
        }
开发者ID:Joncash,项目名称:HanboAOMClassLibrary,代码行数:27,代码来源:AsyncConnectionForm.cs

示例2: InitConnect

        internal void InitConnect(IPEndPoint serverEndPoint,
                                  Action<IPEndPoint, Socket> onConnectionEstablished,
                                  Action<IPEndPoint, SocketError> onConnectionFailed,
                                  ITcpConnection connection,
                                  TimeSpan connectionTimeout)
        {
            if (serverEndPoint == null)
                throw new ArgumentNullException("serverEndPoint");
            if (onConnectionEstablished == null)
                throw new ArgumentNullException("onConnectionEstablished");
            if (onConnectionFailed == null)
                throw new ArgumentNullException("onConnectionFailed");

            var socketArgs = _connectSocketArgsPool.Get();
            var connectingSocket = new Socket(serverEndPoint.AddressFamily, SocketType.Stream, ProtocolType.Tcp);
            socketArgs.RemoteEndPoint = serverEndPoint;
            socketArgs.AcceptSocket = connectingSocket;
            var callbacks = (CallbacksStateToken) socketArgs.UserToken;
            callbacks.OnConnectionEstablished = onConnectionEstablished;
            callbacks.OnConnectionFailed = onConnectionFailed;
            callbacks.PendingConnection = new PendingConnection(connection, DateTime.UtcNow.Add(connectionTimeout));

            AddToConnecting(callbacks.PendingConnection);

            try
            {
                var firedAsync = connectingSocket.ConnectAsync(socketArgs);
                if (!firedAsync)
                    ProcessConnect(socketArgs);
            }
            catch (ObjectDisposedException)
            {
                HandleBadConnect(socketArgs);
            }
        }
开发者ID:jen20,项目名称:tcp-servers-talk,代码行数:35,代码来源:TcpClientConnector.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

        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

示例5: 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

示例6: Server

        private static void Server()
        {
            list = new List<IPAddress>();
            const ushort data_size = 0x400; // = 1024
            byte[] data;
            while (ServerRun)
            {
                Socket sock = new Socket(AddressFamily.InterNetwork,
                          SocketType.Dgram, ProtocolType.Udp);
                IPEndPoint iep = new IPEndPoint(IPAddress.Any, BroadcastRecievePort);
                try
                {
                    sock.Bind(iep);
                    EndPoint ep = (EndPoint)iep;

                    data = new byte[data_size];
                    if (!ServerRun) break;
                    int recv = sock.ReceiveFrom(data, ref ep);
                    string stringData = System.Text.Encoding.ASCII.GetString(data, 0, recv);
                    if (!list.Contains(IPAddress.Parse(ep.ToString().Split(':')[0])))
                        list.Add(IPAddress.Parse(ep.ToString().Split(':')[0]));

                    data = new byte[data_size];
                    if (!ServerRun) break;
                    recv = sock.ReceiveFrom(data, ref ep);
                    stringData = System.Text.Encoding.ASCII.GetString(data, 0, recv);
                    if (!list.Contains(IPAddress.Parse(ep.ToString().Split(':')[0])))
                        list.Add(IPAddress.Parse(ep.ToString().Split(':')[0]));

                    sock.Close();
                }
                catch { }
            }
        }
开发者ID:jiashida,项目名称:super-trojan-horse,代码行数:34,代码来源:BroadcastScan.cs

示例7: Get

        /// <summary>
        /// Gets a list of variable binds.
        /// </summary>
        /// <param name="version">Protocol version.</param>
        /// <param name="endpoint">Endpoint.</param>
        /// <param name="community">Community name.</param>
        /// <param name="variables">Variable binds.</param>
        /// <param name="timeout">The time-out value, in milliseconds. The default value is 0, which indicates an infinite time-out period. Specifying -1 also indicates an infinite time-out period.</param>
        /// <returns></returns>
        public static IList<Variable> Get(VersionCode version, IPEndPoint endpoint, OctetString community, IList<Variable> variables, int timeout)
        {
            if (endpoint == null)
            {
                throw new ArgumentNullException("endpoint");
            }

            if (community == null)
            {
                throw new ArgumentNullException("community");
            }

            if (variables == null)
            {
                throw new ArgumentNullException("variables");
            }

            if (version == VersionCode.V3)
            {
                throw new NotSupportedException("SNMP v3 is not supported");
            }

            var message = new GetRequestMessage(RequestCounter.NextId, version, community, variables);
            var response = message.GetResponse(timeout, endpoint);
            var pdu = response.Pdu();
            if (pdu.ErrorStatus.ToInt32() != 0)
            {
                throw ErrorException.Create(
                    "error in response",
                    endpoint.Address,
                    response);
            }

            return pdu.Variables;
        }
开发者ID:yonglehou,项目名称:sharpsnmplib,代码行数:44,代码来源:Messenger.cs

示例8: Send

 internal void Send(byte[] data, IPEndPoint receiver)
 {
     lock (UDPSocket)
     {
         UDPSocket.SendTo(data, receiver);
     }
 }
开发者ID:ISISComputingGroup,项目名称:EPICS-epicssharp,代码行数:7,代码来源:UdpListener.cs

示例9: CreateConnectingTcpConnection

        public static ITcpConnection CreateConnectingTcpConnection(Guid connectionId, 
                                                                   IPEndPoint remoteEndPoint, 
                                                                   TcpClientConnector connector, 
                                                                   TimeSpan connectionTimeout,
                                                                   Action<ITcpConnection> onConnectionEstablished, 
                                                                   Action<ITcpConnection, SocketError> onConnectionFailed,
                                                                   bool verbose)
        {
            var connection = new TcpConnectionLockless(connectionId, remoteEndPoint, verbose);
// ReSharper disable ImplicitlyCapturedClosure
            connector.InitConnect(remoteEndPoint,
                                  (_, socket) =>
                                  {
                                      if (connection.InitSocket(socket))
                                      {
                                          if (onConnectionEstablished != null)
                                              onConnectionEstablished(connection);
                                          connection.StartReceive();
                                          connection.TrySend();
                                      }
                                  },
                                  (_, socketError) =>
                                  {
                                      if (onConnectionFailed != null)
                                          onConnectionFailed(connection, socketError);
                                  }, connection, connectionTimeout);
// ReSharper restore ImplicitlyCapturedClosure
            return connection;
        }
开发者ID:danieldeb,项目名称:EventStore,代码行数:29,代码来源:TcpConnectionLockless.cs

示例10: serverLoop

        protected void serverLoop()
        {
            Trace.WriteLine("Waiting for UDP messages.");
            listener = new UdpClient(UDP_PORT);
            IPEndPoint groupEP = new IPEndPoint(IPAddress.Any, UDP_PORT);
            byte[] receive_byte_array;

            bool running = true;
            while (running)
            {
                try
                {
                    receive_byte_array = listener.Receive(ref groupEP);
                    if (receive_byte_array.Length != 2)
                    {
                        Trace.WriteLine("Invalid UDP message received. Ignored message!");
                        continue;
                    }

                    Trace.WriteLine("Upp fan speed message received.");
                    int fan = receive_byte_array[0];
                    byte speed = receive_byte_array[1];
                    fanControlDataObject.setPinSpeed(fan, speed, true);
                }
                catch
                {
                    running = false;
                }
            }
        }
开发者ID:futjikato,项目名称:ArduinoFanControl,代码行数:30,代码来源:FanUdpServer.cs

示例11: server_socket

        public server_socket( Object name, int port )
            : base()
        {
            try {
            /* 	    _server_socket = new Socket( AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp ); */
            /* 	    _server_socket.Bind( new IPEndPoint( 0, port ) );          */

            IPEndPoint endpoint;

            if( name != bigloo.foreign.BFALSE ) {
               String server = bigloo.foreign.newstring( name );
               IPHostEntry host = Dns.Resolve(server);
               IPAddress address = host.AddressList[0];
               endpoint = new IPEndPoint(address, port);
            } else {
               endpoint = new IPEndPoint( 0, port );
            }

            _server_socket = new Socket( endpoint.AddressFamily, SocketType.Stream, ProtocolType.Tcp );
            _server_socket.Bind( endpoint );

            _server_socket.Listen( 10 );
             }
             catch (Exception e) {
            socket_error( "make-server-socket",
              "cannot create socket (" + e.Message + ")",
              new bint( port ) );
             }
        }
开发者ID:mbrock,项目名称:bigloo-llvm,代码行数:29,代码来源:server_socket.cs

示例12: Test_Default

        public void Test_Default()
        {
            var config = new ClientConfiguration();
            Assert.AreEqual(1, config.BucketConfigs.Count);

            var bucketConfig = config.BucketConfigs.First().Value;

            IPAddress ipAddress;
            IPAddress.TryParse("127.0.0.1", out ipAddress);
            var endPoint = new IPEndPoint(ipAddress, bucketConfig.Port);
            Assert.AreEqual(endPoint, bucketConfig.GetEndPoint());

            Assert.IsEmpty(bucketConfig.Password);
            Assert.IsEmpty(bucketConfig.Username);
            Assert.AreEqual(11210, bucketConfig.Port);
            Assert.AreEqual("default", bucketConfig.BucketName);

            Assert.AreEqual(2, bucketConfig.PoolConfiguration.MaxSize);
            Assert.AreEqual(1, bucketConfig.PoolConfiguration.MinSize);
            Assert.AreEqual(2500, bucketConfig.PoolConfiguration.RecieveTimeout);
            Assert.AreEqual(2500, bucketConfig.PoolConfiguration.OperationTimeout);
            Assert.AreEqual(10000, bucketConfig.PoolConfiguration.ShutdownTimeout);
            Assert.AreEqual(2500, bucketConfig.DefaultOperationLifespan);
            Assert.AreEqual(75000, config.ViewRequestTimeout);
        }
开发者ID:TDevs,项目名称:couchbase-net-client,代码行数:25,代码来源:ClientConfigurationTests.cs

示例13: 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

示例14: IPEndPoint

        /*
        // TODO: Асинхронная отправка! Или не нужно?
        /// <summary>
        /// Отправить единичное сообщение на единичный хост
        /// </summary>
        /// <param name="text">Текст сообщения</param>
        // internal static void SendMessage(string RemoteHost, string text)
        {
            TcpClient client = null;
            NetworkStream networkStream = null;
            try
            {
                IPEndPoint localEndPoint = new IPEndPoint(IPAddress.Any, 12000);
                // TODO : заменить 127.0.0.1 на что-то более верное
                // TODO: добавить динамическое выделение портов (из пула свободных портов)
                // получатель сообщения при
                IPEndPoint remoteEndPoint = new IPEndPoint(IPAddress.Parse(RemoteHost), 11000);
                // TODO :забить номера портов в настройки
                client = new TcpClient(localEndPoint);

                client.Connect(remoteEndPoint);

                networkStream = client.GetStream();
                byte[] sendBytes = Encoding.UTF8.GetBytes(text);
                networkStream.Write(sendBytes, 0, sendBytes.Length);
                byte[] bytes = new byte[client.ReceiveBufferSize];
                networkStream.Read(bytes, 0, client.ReceiveBufferSize);
                string returnData = Encoding.UTF8.GetString(bytes);
                //MessageBox.Show(returnData);
            }
            catch (Exception e)
            {
                MessageBox.Show(e.Message);
            }
            finally
            {
                if (networkStream != null) networkStream.Close();
                if (client!=null) client.Close();

            }

        }
        */
        // реализаця с UDP
        internal static void SendMessage(string RemoteHost, string text)
        {
            UdpClient client = null;
            try
            {
                IPEndPoint localEndPoint = new IPEndPoint(IPAddress.Any, 12000);

                // получатель сообщения при
                IPEndPoint remoteEndPoint = new IPEndPoint(IPAddress.Parse(RemoteHost), 11000);
                // TODO :забить номера портов в настройки
                client = new UdpClient(localEndPoint);

                byte[] sendBytes = Encoding.ASCII.GetBytes(text);
                networkStream.Write(sendBytes, 0, sendBytes.Length);
                byte[] bytes = new byte[client.ReceiveBufferSize];
                networkStream.Read(bytes, 0, client.ReceiveBufferSize);
                string returnData = Encoding.UTF8.GetString(bytes);
                //MessageBox.Show(returnData);
            }
            catch (Exception e)
            {
                MessageBox.Show(e.Message);
            }
            finally
            {
                if (networkStream != null) networkStream.Close();
                if (client != null) client.Close();

            }
        }
开发者ID:IlyichTrue,项目名称:NetSend,代码行数:74,代码来源:NetworkBasic.cs

示例15: ConnectAsync

 public Task<Socket> ConnectAsync(IPEndPoint remoteEndPoint)
 {
     _connectTcs = new TaskCompletionSource<Socket>();
     var task = _connectTcs.Task;
     Connect(remoteEndPoint);
     return task;
 }
开发者ID:SaladLab,项目名称:Akka.Interfaced.SlimSocket,代码行数:7,代码来源:TcpConnector.cs


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