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


C# Socket.SendTo方法代码示例

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


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

示例1: StartListener

    private static void StartListener()
    {
        //Initiate UDP server
        Socket s = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp);
        UdpClient listener = new UdpClient(ListenPort);
        IPEndPoint groupEp = new IPEndPoint(IPAddress.Any,ListenPort);
        IPEndPoint responseEp;
        string receivedCommand;

        try
        {
            while (true)
            {
                //Wait for incoming command
                Console.WriteLine("Waiting for command");
                byte[] bytes = listener.Receive( ref groupEp);
                receivedCommand = Encoding.ASCII.GetString(bytes,0,bytes.Length);
                Console.WriteLine("Received command: " + receivedCommand + " from " + groupEp.Address);

                //Send matching response
                responseEp = new IPEndPoint(groupEp.Address, ListenPort);
                if (receivedCommand == "U" || receivedCommand ==  "u")
                {
                    using (StreamReader sr = new StreamReader ("/proc/uptime"))
                    {
                        String line = sr.ReadToEnd();
                        Console.WriteLine("Sending uptime: " + line);

                        byte[] sendbuf = Encoding.ASCII.GetBytes(line);
                        s.SendTo(sendbuf, responseEp);
                    }
                }
                else if(receivedCommand == "L" || receivedCommand ==  "l")
                {
                    using (StreamReader sr = new StreamReader ("/proc/loadavg"))
                    {
                        String line = sr.ReadToEnd();
                        Console.WriteLine("Sending load average: " + line);

                        byte[] sendbuf = Encoding.ASCII.GetBytes(line);
                        s.SendTo(sendbuf, responseEp);
                    }
                }
                else
                {
                    Console.WriteLine("Command " + receivedCommand + " not found\n");
                    byte[] sendbuf = Encoding.ASCII.GetBytes("Input not recognized, please try again!");
                    s.SendTo(sendbuf, responseEp);
                }
            }
        }
        catch (Exception e)
        {
            Console.WriteLine(e.ToString());
        }
        finally
        {
            listener.Close();
        }
    }
开发者ID:BjornNorgaard,项目名称:I4IKN,代码行数:60,代码来源:ListenerCode.cs

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

示例3: Success

        public void Success()
        {
            if (Socket.OSSupportsIPv4)
            {
                using (Socket receiver = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp))
                {
                    int port = receiver.BindToAnonymousPort(IPAddress.Loopback);
                    receiver.SetSocketOption(SocketOptionLevel.IP, SocketOptionName.PacketInformation, true);

                    Socket sender = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp);
                    sender.Bind(new IPEndPoint(IPAddress.Loopback, 0));
                    sender.SendTo(new byte[1024], new IPEndPoint(IPAddress.Loopback, port));

                    IPPacketInformation packetInformation;
                    SocketFlags flags = SocketFlags.None;
                    EndPoint remoteEP = new IPEndPoint(IPAddress.Any, 0);

                    int len = receiver.ReceiveMessageFrom(new byte[1024], 0, 1024, ref flags, ref remoteEP, out packetInformation);

                    Assert.Equal(1024, len);
                    Assert.Equal(sender.LocalEndPoint, remoteEP);
                    Assert.Equal(((IPEndPoint)sender.LocalEndPoint).Address, packetInformation.Address);

                    sender.Dispose();
                }
            }
        }
开发者ID:er0dr1guez,项目名称:corefx,代码行数:27,代码来源:ReceiveMessageFrom.cs

示例4: GetNonDefaultIPPacketInformation

        private IPPacketInformation GetNonDefaultIPPacketInformation()
        {
            const int ReceiveTimeout = 5000;

            using (var receiver = new Socket(SocketType.Dgram, ProtocolType.Udp))
            using (var sender = new Socket(SocketType.Dgram, ProtocolType.Udp))
            {
                int port = receiver.BindToAnonymousPort(IPAddress.Loopback);

                var waitHandle = new ManualResetEvent(false);

                SocketAsyncEventArgs receiveArgs = new SocketAsyncEventArgs {
                    RemoteEndPoint = new IPEndPoint(IPAddress.Loopback, port),
                    UserToken = waitHandle
                };

                receiveArgs.SetBuffer(new byte[1], 0, 1);
                receiveArgs.Completed += (_, args) => ((ManualResetEvent)args.UserToken).Set();

                Assert.True(receiver.ReceiveMessageFromAsync(receiveArgs));

                sender.SendTo(new byte[1], new IPEndPoint(IPAddress.Loopback, port));

                Assert.True(waitHandle.WaitOne(ReceiveTimeout));

                return receiveArgs.ReceiveMessageFromPacketInfo;
            }
        }
开发者ID:vbouret,项目名称:corefx,代码行数:28,代码来源:IPPacketInformationTest.cs

示例5: GetNonDefaultIPPacketInformation

        private IPPacketInformation GetNonDefaultIPPacketInformation()
        {
            const int ReceiveTimeout = 5000;

            using (var receiver = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp))
            using (var sender = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp))
            {
                int port = receiver.BindToAnonymousPort(IPAddress.Loopback);

                var waitHandle = new ManualResetEvent(false);

                SocketAsyncEventArgs receiveArgs = new SocketAsyncEventArgs {
                    RemoteEndPoint = new IPEndPoint(IPAddress.Loopback, port),
                    UserToken = waitHandle
                };

                receiveArgs.SetBuffer(new byte[1], 0, 1);
                receiveArgs.Completed += (_, args) => ((ManualResetEvent)args.UserToken).Set();

                Assert.True(receiver.ReceiveMessageFromAsync(receiveArgs));

                // Send a few packets, in case they aren't delivered reliably.
                for (int i = 0; i < Configuration.UDPRedundancy; i++)
                {
                    sender.SendTo(new byte[1], new IPEndPoint(IPAddress.Loopback, port));
                }

                Assert.True(waitHandle.WaitOne(ReceiveTimeout));

                return receiveArgs.ReceiveMessageFromPacketInfo;
            }
        }
开发者ID:SGuyGe,项目名称:corefx,代码行数:32,代码来源:IPPacketInformationTest.cs

示例6: BangChengMessageBYSocket

    public string BangChengMessageBYSocket()
    {
        IPAddress serverIPAddress = IPAddress.Parse("127.0.0.1");//服务IP地址
            int serverPort = 10001;//端口号
            _client = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp);
            _remoteEndPoint = new IPEndPoint(serverIPAddress, serverPort);

            string Command = "Subscribe";//类型(订阅Subscribe/停止订阅UnSubscribe/发布Publish)

            string message = Command + "," + "1001";
            _client.SendTo(Encoding.ASCII.GetBytes(message), _remoteEndPoint);
            _data = new byte[1024];
            try
            {
                EndPoint publisherEndPoint = _client.LocalEndPoint;
                 _recv = _client.ReceiveFrom(_data, ref publisherEndPoint);
                string msg = Encoding.ASCII.GetString(_data, 0, _recv) + "," + publisherEndPoint.ToString();
                string value = msg.Split(",".ToCharArray())[1].ToString();
                return string.Format("{0:F2}", value);

            }
            catch
            {
                return "0";
            }
    }
开发者ID:SaintLoong,项目名称:HanCheng_CoalTraffic_BS,代码行数:26,代码来源:text.aspx.cs

示例7: Success

        public void Success()
        {
            ManualResetEvent completed = new ManualResetEvent(false);

            if (Socket.OSSupportsIPv4)
            {
                using (Socket receiver = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp))
                {
                    int port = receiver.BindToAnonymousPort(IPAddress.Loopback);
                    receiver.SetSocketOption(SocketOptionLevel.IP, SocketOptionName.PacketInformation, true);

                    Socket sender = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp);
                    sender.Bind(new IPEndPoint(IPAddress.Loopback, 0));
                    sender.SendTo(new byte[1024], new IPEndPoint(IPAddress.Loopback, port));

                    SocketAsyncEventArgs args = new SocketAsyncEventArgs();
                    args.RemoteEndPoint = new IPEndPoint(IPAddress.Any, 0);
                    args.SetBuffer(new byte[1024], 0, 1024);
                    args.Completed += OnCompleted;
                    args.UserToken = completed;

                    Assert.True(receiver.ReceiveMessageFromAsync(args));

                    Assert.True(completed.WaitOne(Configuration.PassingTestTimeout), "Timeout while waiting for connection");

                    Assert.Equal(1024, args.BytesTransferred);
                    Assert.Equal(sender.LocalEndPoint, args.RemoteEndPoint);
                    Assert.Equal(((IPEndPoint)sender.LocalEndPoint).Address, args.ReceiveMessageFromPacketInfo.Address);

                    sender.Dispose();
                }
            }
        }
开发者ID:rainersigwald,项目名称:corefx,代码行数:33,代码来源:ReceiveMessageFromAsync.cs

示例8: GetNTPTime

        /// <summary>
        /// Get time from NTP server
        /// </summary>
        /// <param name="timeServer">Time server to use</param>
        /// <param name="gmtOffset">GMT offset in minutes</param>
        /// <returns>NTP date-time or DateTime.MinValue when an error has occured.</returns>
        public DateTime GetNTPTime(string timeServer, int gmtOffset = 0)
        {
            this.lastErrorMsg = "";
            Socket s = null;
            try
            {
                // init socket
                EndPoint remoteEP = new IPEndPoint(Dns.GetHostEntry(timeServer).AddressList[0], 123);
                s = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp);

                // init request
                byte[] ntpData = new byte[48];
                Array.Clear(ntpData, 0, 48);
                ntpData[0] = 0x1B; // set protocol version

                // send request
                s.SendTo(ntpData, remoteEP);

                // wait 30s if no response, timeout
                if (s.Poll(30 * 1000 * 1000, SelectMode.SelectRead))
                {
                    // get response
                    s.ReceiveFrom(ntpData, ref remoteEP);

                    s.Close();

                    // parse time value
                    byte offsetTransmitTime = 40;
                    ulong intpart = 0;
                    ulong fractpart = 0;
                    for (int i = 0; i <= 3; i++) intpart = (intpart << 8) | ntpData[offsetTransmitTime + i];
                    for (int i = 4; i <= 7; i++) fractpart = (fractpart << 8) | ntpData[offsetTransmitTime + i];
                    ulong milliseconds = (intpart * 1000 + (fractpart * 1000) / 0x100000000L);

                    DateTime ntpTime = new DateTime(1900, 1, 1) + TimeSpan.FromTicks((long)milliseconds * TimeSpan.TicksPerMillisecond);

                    return ntpTime.AddMinutes(gmtOffset);
                }
                else
                {
                    // timeout
                    s.Close();
                    this.lastErrorMsg = "Timed out.";
                }
            }
            catch (Exception e)
            {
                try
                {
                    s.Close();
                }
                catch { }
                this.lastErrorMsg = e.Message;
            }

            return DateTime.MinValue;
        }
开发者ID:Gorgok,项目名称:Fishy-Brains,代码行数:63,代码来源:NTPClient.cs

示例9: OnClickSend

    public void OnClickSend()
    {
        socket = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp);

        byte[] buffer = System.Text.Encoding.UTF8.GetBytes("[UDP] this is client: " + count);
        IPEndPoint endpoint = new IPEndPoint(IPAddress.Parse(address), port);
        socket.SendTo(buffer, buffer.Length, SocketFlags.None, endpoint);

        count++;
    }
开发者ID:cckato,项目名称:UniChat,代码行数:10,代码来源:UdpServer.cs

示例10: Socket_SendToDnsEndPoint_ArgumentException

 public void Socket_SendToDnsEndPoint_ArgumentException()
 {
     using (Socket sock = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp))
     {
         Assert.Throws<ArgumentException>(() =>
         {
             sock.SendTo(new byte[10], new DnsEndPoint("localhost", UnusedPort));
         });
     }
 }
开发者ID:shmao,项目名称:corefx,代码行数:10,代码来源:DnsEndPointTest.cs

示例11: 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 list = new List<Socket> { firstReceiver, secondReceiver };
                Socket.Select(list, null, null, SelectSuccessTimeout);

                Assert.Equal(2, list.Count);
                Assert.Equal(firstReceiver, list[0]);
                Assert.Equal(secondReceiver, list[1]);
            }
        }
开发者ID:natemcmaster,项目名称:corefx,代码行数:23,代码来源:SelectAndPollTests.cs

示例12: Networking

    public Networking()
    {
        socket = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp);
        socket.ReceiveTimeout = receiveTimeout;

        recbuf = new byte[receiveBufferSize];

        IPAddress ipaddr = IPAddress.Parse(serverAddress);
        IPEndPoint ep = new IPEndPoint(ipaddr, serverPort);
        server = (EndPoint)(new IPEndPoint(IPAddress.Any, clientPort));

        socket.SendTo(Encoding.ASCII.GetBytes(SYN_MSG), ep);
        socket.ReceiveFrom(recbuf, ref server);
        Send(ACK_MSG);
    }
开发者ID:doubleyou,项目名称:u3d-experiments,代码行数:15,代码来源:Network.cs

示例13: SelectRead_Single_Success

        public void SelectRead_Single_Success()
        {
            using (var receiver = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp))
            using (var sender = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp))
            {
                int receiverPort = receiver.BindToAnonymousPort(IPAddress.Loopback);
                var receiverEndpoint = new IPEndPoint(IPAddress.Loopback, receiverPort);

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

                var list = new List<Socket> { receiver };
                Socket.Select(list, null, null, SelectSuccessTimeoutMicroseconds);

                Assert.Equal(1, list.Count);
                Assert.Equal(receiver, list[0]);
            }
        }
开发者ID:er0dr1guez,项目名称:corefx,代码行数:17,代码来源:SelectAndPollTests.cs

示例14: Main

    static void Main(string[] args)
    {
        Socket s = new Socket(AddressFamily.InterNetwork, SocketType.Dgram,
            ProtocolType.Udp);

        IPAddress broadcast = IPAddress.Parse("188.166.29.138");

        byte[] sendbuf = Encoding.ASCII.GetBytes("u");
        IPEndPoint ep = new IPEndPoint(broadcast, 12345);

        s.SendTo(sendbuf, ep);

        Console.WriteLine("Message sent to the broadcast address");

        sendbuf = new byte[100];
        s.Receive(sendbuf);

        Console.WriteLine("Received: {0}", Encoding.ASCII.GetString(sendbuf));
    }
开发者ID:MartinCarpentier,项目名称:I4IKN,代码行数:19,代码来源:Program.cs

示例15: Main

    static void Main(string[] args)
    {
        //Setup UDP client
        int listenport = 9000;
        UdpClient listener = new UdpClient (listenport);
        Socket s = new Socket (AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp);

        //Initialize ip and command from args
        IPAddress sendIP = IPAddress.Parse (args[0]);
        string sendCommand = args[1];

        //Send command
        byte[] sendbuf = Encoding.ASCII.GetBytes (sendCommand);
        IPEndPoint sendEP = new IPEndPoint (sendIP, listenport);
        s.SendTo (sendbuf, sendEP);

        //Wait for answer and output to console
        byte[] bytes = listener.Receive (ref sendEP);
        Console.WriteLine (Encoding.ASCII.GetString (bytes, 0, bytes.Length));
    }
开发者ID:BjornNorgaard,项目名称:I4IKN,代码行数:20,代码来源:TalkerCode.cs


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