• 设为首页
  • 点击收藏
  • 手机版
    手机扫一扫访问
    迪恩网络手机版
  • 关注官方公众号
    微信扫一扫关注
    迪恩网络公众号

C# IPEndPoint类代码示例

原作者: [db:作者] 来自: [db:来源] 收藏 邀请

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



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

示例1: StartListener

 private void StartListener(IPEndPoint endPoint)
 {
     _listener = new TcpListener(endPoint);
     _listener.Start(5);
     _log.WriteLine("Server {0} listening", endPoint.Address.ToString());
     _listener.AcceptTcpClientAsync().ContinueWith(t => OnAccept(t), TaskScheduler.Default);
 }
开发者ID:SGuyGe,项目名称:corefx,代码行数:7,代码来源:DummyTcpServer.cs


示例2: SyncClient

 public SyncClient()
 {
     var hostName = Dns.GetHostName();
     var localAdd = Dns.GetHostEntry(hostName).AddressList[0];
     var localEP = new IPEndPoint(localAdd, 0);
     TcpClient = new TcpClient(); //new TcpClient(localEP);
 }
开发者ID:erashid,项目名称:Extensions,代码行数:7,代码来源:SyncClient.cs


示例3: init

 public void init()
 {
     IP = "192.168.15.11";
     port = 8051;
     remoteEndPoint = new IPEndPoint(IPAddress.Parse(IP), port);
     client = new UdpClient();
 }
开发者ID:RoySquad,项目名称:KSP_Remote,代码行数:7,代码来源:UDP_Sender.cs


示例4: Main

    public static void Main()
    {
        byte[] data = new byte[1024];
          IPEndPoint ipep = new IPEndPoint(IPAddress.Any, 9876);
          UdpClient newsock = new UdpClient(ipep);

          Console.WriteLine("Waiting for a client...");

          IPEndPoint sender = new IPEndPoint(IPAddress.Any, 9877);

          data = newsock.Receive(ref sender);

          Console.WriteLine("Message received from {0}:", sender.ToString());
          Console.WriteLine(Encoding.ASCII.GetString(data, 0, data.Length));

          string msg = Encoding.ASCII.GetString(data, 0, data.Length);
          data = Encoding.ASCII.GetBytes(msg);
          newsock.Send(data, data.Length, sender);

          while(true){
         data = newsock.Receive(ref sender);

         Console.WriteLine(Encoding.ASCII.GetString(data, 0, data.Length));
         newsock.Send(data, data.Length, sender);
          }
    }
开发者ID:Kaerit,项目名称:IsoMonksComm,代码行数:26,代码来源:server.cs


示例5: Start

    void Start()
    {
        Application.runInBackground = true;
        Debug.Log("Net listener started!");
        // Data buffer for incoming data.
        bytes = new byte[1024];

        // Connect to a remote device.
        try
        {
            // Establish the remote endpoint for the socket.
            // This example uses port 30303 on the local computer.
            IPHostEntry ipHostInfo = Dns.GetHostEntry("localhost");
            IPAddress ipAddress = ipHostInfo.AddressList[0];
            remoteEP = new IPEndPoint(ipAddress, 30303);

            // Create a TCP/IP  socket.
            socket = new Socket(AddressFamily.InterNetwork,
                SocketType.Stream, ProtocolType.Tcp);

            socket.Connect(remoteEP);
            Debug.Log("Socket connected to {0}" +
                socket.RemoteEndPoint.ToString());

            idMap = new Dictionary<int, GameObject>();

            socket.Blocking = false;
        }
        catch (Exception e)
        {
            Debug.Log(e.ToString());
        }
    }
开发者ID:jeKnowledge,项目名称:univrse-unity-client,代码行数:33,代码来源:ConnectToHaxe.cs


示例6: Start

 // Use this for initialization
 void Start()
 {
     // Set up Server End Point for sending packets.
     IPHostEntry serverHostEntry = Dns.GetHostEntry(serverIp);
     IPAddress serverIpAddress = serverHostEntry.AddressList[0];
     serverEndPoint = new IPEndPoint(serverIpAddress, serverPort);
     Debug.Log("Server IPEndPoint: " + serverEndPoint.ToString());
     // Set up Client End Point for receiving packets.
     IPHostEntry clientHostEntry = Dns.GetHostEntry(Dns.GetHostName());
     IPAddress clientIpAddress = IPAddress.Any;
     foreach (IPAddress ip in clientHostEntry.AddressList) {
         if (ip.AddressFamily == AddressFamily.InterNetwork) {
             clientIpAddress = ip;
         }
     }
     clientEndPoint = new IPEndPoint(clientIpAddress, serverPort);
     Debug.Log("Client IPEndPoint: " + clientEndPoint.ToString());
     // Create socket for client and bind to Client End Point (Ip/Port).
     clientSocket = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp);
     try {
         clientSocket.Bind(clientEndPoint);
     }
     catch (Exception e) {
         Debug.Log("Winsock error: " + e.ToString());
     }
 }
开发者ID:Victory-Game-Studios,项目名称:Oldentide,代码行数:27,代码来源:NetworkInterface.cs


示例7: ReceiveData

	private  void ReceiveData()
	{
		client = new UdpClient(8000);
		while (running)
		{			
			try
			{
				IPEndPoint anyIP = new IPEndPoint(IPAddress.Any, 0);
				byte[] data = client.Receive(ref anyIP);				
				
				string text = Encoding.UTF8.GetString(data);
				Debug.Log("Input "+text);
				string[] info = text.Split(':');
				
				inputText = text;
				
				if(info[0].Equals("speed")){
					speed= info[1];
				}
				if(info[0].Equals("turn")){
					axis= info[1];
				}
				
				
			}
			catch (Exception err)
			{
				running =false;
				print(err.ToString());
			}
		}
	}
开发者ID:tattoxcm,项目名称:VRBike,代码行数:32,代码来源:NetworkScript.cs


示例8: Connect

	void Connect()
	{
		Debug.Log ("Connect");

		//if (clientSocket != null && clientSocket.Connected) Disconnect();

		//var ipAddress = Dns.GetHostAddresses ("localhost");
		//IPEndPoint ipEndPoint = new IPEndPoint(ipAddress[0], 1234);
		IPEndPoint ipEndPoint = new IPEndPoint(IPAddress.Parse(hostIp), port);
		
		// Create Socket
		AddressFamily family  = AddressFamily.InterNetwork;
		SocketType    sokType = SocketType.Stream;
		ProtocolType  proType = ProtocolType.Tcp;
		clientSocket = new Socket(family, sokType, proType);
		
		Debug.Log("Connecting to localhost");
		clientSocket.Connect (ipEndPoint);
		
		// arriving here means the operation completed asyncConnect.IsCompleted = true)
		// but not necessarily successfully
		if (clientSocket.Connected == false)
		{
			Debug.Log(".client is not connected.");
			return;
		}
		
		Debug.Log(".client is connected.");
		
		clientSocket.Blocking = false;


	}
开发者ID:deeni,项目名称:vive,代码行数:33,代码来源:MocapSocket.cs


示例9: UDPServer

	public UDPServer()
	{
		try
		{
			// Iniciando array de clientes conectados
			this.listaClientes = new ArrayList();
			entrantPackagesCounter = 0;
			sendingPackagesCounter = 0;			
			// Inicializando el delegado para actualizar estado
			//this.updateStatusDelegate = new UpdateStatusDelegate(this.UpdateStatus);
		
			// Inicializando el socket
			serverSocket = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp);
			
			// Inicializar IP y escuhar puerto 30000
			IPEndPoint server = new IPEndPoint(IPAddress.Any, 30001);
			
			// Asociar socket con el IP dado y el puerto
			serverSocket.Bind(server);
			
			// Inicializar IPEndpoint de los clientes
			IPEndPoint clients = new IPEndPoint(IPAddress.Any, 0);
			
			// Inicializar Endpoint de clientes
			EndPoint epSender = (EndPoint)clients;
			
			// Empezar a escuhar datos entrantes
			serverSocket.BeginReceiveFrom(this.dataStream, 0, this.dataStream.Length, SocketFlags.None, ref epSender, new AsyncCallback(ReceiveData), epSender);

		}
		catch (Exception ex)
		{
			//Debug.Log("Error al cargar servidor: " + ex.Message+ " ---UDP ");
		}
	}
开发者ID:PJEstrada,项目名称:proyecto1-redes,代码行数:35,代码来源:UDPServer.cs


示例10: Start

    public void Start(int port)
    {
        if (listener != null && listener.Server.IsBound)
        {
            return;
        }

        this.port = port;

        IPEndPoint ipEnd = new IPEndPoint(IPAddress.Any, port);
        listener = new TcpListener(ipEnd);

        try
        {
            listener.Start();
            running = true;
            if (LOGGER.IsInfoEnabled)
            {
                LOGGER.Info("Push Server Simulator is successfully started on port " + port.ToString());
            }
        }
        catch (Exception e)
        {
            if (LOGGER.IsErrorEnabled)
            {
                LOGGER.Error("Error occured while trying to start Push Server Simulator on port " + port.ToString() + " . Message: " + e.Message);
            }
        }

        thread = new Thread(new ThreadStart(listen));
        thread.Start();
    }
开发者ID:jcamelina,项目名称:oneapi-dot-net,代码行数:32,代码来源:PushServerSimulator.cs


示例11: ConnectSocket

	Socket ConnectSocket(string server, int port) {
		Socket s = null;
		IPHostEntry hostEntry = null;

		// Get host related information.
		hostEntry = Dns.GetHostEntry(server);

		// Loop through the AddressList to obtain the supported AddressFamily. This is to avoid
		// an exception that occurs when the host IP Address is not compatible with the address family
		// (typical in the IPv6 case).
		foreach(IPAddress address in hostEntry.AddressList) {
			IPEndPoint ipe = new IPEndPoint(address, port);
			Socket tempSocket = new Socket(ipe.AddressFamily, SocketType.Stream, ProtocolType.Tcp);

			tempSocket.Connect(ipe);

			if(tempSocket.Connected) {
				s = tempSocket;
				break;
			} else {
				continue;
			}
		}
		return s;
	}
开发者ID:diogorbg,项目名称:BQuest,代码行数:25,代码来源:WebSocket.cs


示例12: Connect

    public bool Connect()
    {
        try
        {

            serverRemote = new IPEndPoint(IPAddress.Parse(ipAddress), portNumber);
            udpClient = new UdpClient();
            udpClient.Connect(serverRemote);
            if(udpClient.Client.Connected)
            {
                Debug.Log("connected!");
                sendUDPPacket("ANYONE OUT THERE?");

            //byte[] data = Encoding.UTF8.GetBytes(toSend);

            //client.Send(data, data.Length, serverRemote);
            //client.SendTimeout(serverRemote, data);

            }

        }
        catch(Exception ex)
        {
            print ( ex.Message + " : OnConnect");
        }
        isConnected = true;
        if ( udpClient == null ) return false;
        return udpClient.Client.Connected;
    }
开发者ID:putty174,项目名称:Pong,代码行数:29,代码来源:Sockets.cs


示例13: Receive

    public Byte[] Receive(ref IPEndPoint remoteEP)
    {
      Contract.Ensures(Contract.Result<Byte[]>() != null);
      Contract.Ensures(Contract.Result<Byte[]>().Length > 0); // after reading the code

      return default(Byte[]);
    }
开发者ID:asvishnyakov,项目名称:CodeContracts,代码行数:7,代码来源:System.Net.Sockets.UdpClient.cs


示例14: ConnectToServer

    void ConnectToServer()
    {
        clientSocket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
        //服务器IP地址
        IPAddress ip = IPAddress.Parse(ipaddress);
        //服务器端口
        IPEndPoint ipEndpoint = new IPEndPoint(ip, port);

       // clientSocket.Connect(new IPEndPoint(IPAddress.Parse(ipaddress), port));
        //这是一个异步的建立连接,当连接建立成功时调用connectCallback方法
        IAsyncResult result = clientSocket.BeginConnect(ipEndpoint, new AsyncCallback(connectCallback), clientSocket);
        //这里做一个超时的监测,当连接超过5秒还没成功表示超时
        bool success = result.AsyncWaitHandle.WaitOne(5000, true);
        if (!success)
        {
            //超时
            //Closed();
            Debug.Log("connect Time Out");
        }
        else
        {
            //与socket建立连接成功,开启线程接受服务端数据。
            //worldpackage = new List<JFPackage.WorldPackage>();
            //Thread thread = new Thread(new ThreadStart(ReceiveSorket));
            t = new Thread(RecevieMessage);
            t.IsBackground = true;
            t.Start();
        }

       
    }
开发者ID:wtuickqmq,项目名称:BadugiPokerClient,代码行数:31,代码来源:SocketManager.cs


示例15: Connection

    public void Connection()
    {
        if(!connected)
        {
            string ip = IP.text;
            Debug.Log("[CLIENT] Connecting to Server [" + ip + ":" + port + "]");

            try
            {
                IPAddress ipAdress = IPAddress.Parse(ip);
                IPEndPoint remoteEP = new IPEndPoint(ipAdress, port);
                PlayerPrefs.SetString ("IP_Address", ip);
                // Create a TCP/IP socket.
                client = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);

                // Connect to the remote endpoint.
                client.BeginConnect( remoteEP, new AsyncCallback(ConnectCallback), client);
                connectDone.WaitOne();

                Receive(client);

            }
            catch (Exception e)
            {
                distributor.closeConnection();
            }
        }
        else
        {
            Application.Quit();
        }
    }
开发者ID:stefanseibert,项目名称:padawan101,代码行数:32,代码来源:RotationDistributor.cs


示例16: ParseActiveTcpListenersFromFiles

        internal static IPEndPoint[] ParseActiveTcpListenersFromFiles(string tcp4ConnectionsFile, string tcp6ConnectionsFile)
        {
            if (!File.Exists(tcp4ConnectionsFile) || !File.Exists(tcp6ConnectionsFile))
            {
                throw new PlatformNotSupportedException(SR.net_InformationUnavailableOnPlatform);
            }

            string tcp4FileContents = File.ReadAllText(tcp4ConnectionsFile);
            string[] v4connections = tcp4FileContents.Split(s_newLineSeparator, StringSplitOptions.RemoveEmptyEntries);

            string tcp6FileContents = File.ReadAllText(tcp6ConnectionsFile);
            string[] v6connections = tcp6FileContents.Split(s_newLineSeparator, StringSplitOptions.RemoveEmptyEntries);

            /// First line is header in each file.
            IPEndPoint[] endPoints = new IPEndPoint[v4connections.Length + v6connections.Length - 2];
            int index = 0;

            // TCP Connections
            for (int i = 1; i < v4connections.Length; i++) // Skip first line header.
            {
                string line = v4connections[i];
                IPEndPoint endPoint = ParseLocalConnectionInformation(line);
                endPoints[index++] = endPoint;
            }

            // TCP6 Connections
            for (int i = 1; i < v6connections.Length; i++) // Skip first line header.
            {
                string line = v6connections[i];
                IPEndPoint endPoint = ParseLocalConnectionInformation(line);
                endPoints[index++] = endPoint;
            }

            return endPoints;
        }
开发者ID:ardacetinkaya,项目名称:corefx,代码行数:35,代码来源:StringParsingHelpers.Connections.cs


示例17: Receive

 private void Receive(IAsyncResult ar)
 {
     IPEndPoint ip = new IPEndPoint(IPAddress.Any, 15000);
     byte[] bytes = udp.EndReceive(ar, ref ip);
     string message = Encoding.ASCII.GetString(bytes);
     StartListening();
 }
开发者ID:Supaidaman,项目名称:MasterServerController,代码行数:7,代码来源:Receiver.cs


示例18: SelectRead_Multiple_Success

        public void SelectRead_Multiple_Success()
        {
            using (var firstReceiver = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp))
            using (var secondReceiver = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp))
            using (var sender = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp))
            {
                int firstReceiverPort = firstReceiver.BindToAnonymousPort(IPAddress.Loopback);
                var firstReceiverEndpoint = new IPEndPoint(IPAddress.Loopback, firstReceiverPort);

                int secondReceiverPort = secondReceiver.BindToAnonymousPort(IPAddress.Loopback);
                var secondReceiverEndpoint = new IPEndPoint(IPAddress.Loopback, secondReceiverPort);

                sender.SendTo(new byte[1], SocketFlags.None, firstReceiverEndpoint);
                sender.SendTo(new byte[1], SocketFlags.None, secondReceiverEndpoint);

                var sw = Stopwatch.StartNew();
                Assert.True(SpinWait.SpinUntil(() =>
                {
                    var list = new List<Socket> { firstReceiver, secondReceiver };
                    Socket.Select(list, null, null, Math.Max((int)(SelectSuccessTimeoutMicroseconds - (sw.Elapsed.TotalSeconds * 1000000)), 0));
                    Assert.True(list.Count <= 2);
                    if (list.Count == 2)
                    {
                        Assert.Equal(firstReceiver, list[0]);
                        Assert.Equal(secondReceiver, list[1]);
                        return true;
                    }
                    return false;
                }, SelectSuccessTimeoutMicroseconds / 1000), "Failed to select both items within allotted time");
            }
        }
开发者ID:er0dr1guez,项目名称:corefx,代码行数:31,代码来源:SelectAndPollTests.cs


示例19: UdpClient

        // Creates a new instance of the UdpClient class that communicates on the
        // specified port number.
        public UdpClient(int port, AddressFamily family)
        {
            // Validate input parameters.
            if (!TcpValidationHelpers.ValidatePortNumber(port))
            {
                throw new ArgumentOutOfRangeException("port");
            }

            // Validate the address family.
            if (family != AddressFamily.InterNetwork && family != AddressFamily.InterNetworkV6)
            {
                throw new ArgumentException(SR.net_protocol_invalid_family, "family");
            }

            IPEndPoint localEP;
            _family = family;

            if (_family == AddressFamily.InterNetwork)
            {
                localEP = new IPEndPoint(IPAddress.Any, port);
            }
            else
            {
                localEP = new IPEndPoint(IPAddress.IPv6Any, port);
            }

            CreateClientSocket();

            _clientSocket.Bind(localEP);
        }
开发者ID:nbilling,项目名称:corefx,代码行数:32,代码来源:UDPClient.cs


示例20: Connect

    public static bool Connect(IPEndPoint remoteEndPoint, int timeoutMSec)
    {
        TimeoutObject.Reset();
        socketexception = null;

        string serverip = Convert.ToString(remoteEndPoint.Address);
        int serverport = remoteEndPoint.Port;
        TcpClient tcpclient = new TcpClient();

        tcpclient.BeginConnect(serverip, serverport, new AsyncCallback(CallBackMethod), tcpclient);

        if (TimeoutObject.WaitOne(timeoutMSec, false))
        {
            if (IsConnectionSuccessful)
            {
                tcpclient.Close();
                return true;
            }
            else
            {
                tcpclient.Close();
                return false;
            }
        }
        else
        {
            tcpclient.Close();
            return false;
        }
    }
开发者ID:UkiMiawz,项目名称:data-communication,代码行数:30,代码来源:NetworkHelper.cs



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


鲜花

握手

雷人

路过

鸡蛋
该文章已有0人参与评论

请发表评论

全部评论

专题导读
上一篇:
C# IPackage类代码示例发布时间:2022-05-24
下一篇:
C# IPEImage类代码示例发布时间:2022-05-24
热门推荐
阅读排行榜

扫描微信二维码

查看手机版网站

随时了解更新最新资讯

139-2527-9053

在线客服(服务时间 9:00~18:00)

在线QQ客服
地址:深圳市南山区西丽大学城创智工业园
电邮:jeky_zhao#qq.com
移动电话:139-2527-9053

Powered by 互联科技 X3.4© 2001-2213 极客世界.|Sitemap