Exiting a UDP listen routine





.everyoneloves__top-leaderboard:empty,.everyoneloves__mid-leaderboard:empty,.everyoneloves__bot-mid-leaderboard:empty{ height:90px;width:728px;box-sizing:border-box;
}







1















I am trying to write a routine in powershell which will listen on a UDP port, then exit when a key is pressed. The problem I have is that the program will only exit after a datagram has been read.



I.e. It will read n values, user will hit F12, program will wait until it gets the n+1th value, then exit.



What should happen is: reads n values, user will hit F12, program should shut down.



$endpoint = New-Object System.Net.IPEndPoint ([IPAddress]::Any, $port)
$continue = $true
while($continue)
{

if ([console]::KeyAvailable)
{
echo "Exit with F12";
$x = [System.Console]::ReadKey()

switch ( $x.key)
{
F12 { $continue = $false }
}
}
else
{

$socket = New-Object System.Net.Sockets.UdpClient $port
$content = $socket.Receive([ref]$endpoint)
$socket.Close()
[Text.Encoding]::ASCII.GetString($content)
}
}


I'm completely new to Powershell, so maybe this isn't possible. The rest of the code has been stolen from other answers here.










share|improve this question


















  • 1





    The Receive method is blocking : it will halt until a datagram has been received. Either use an async version or set the receivetimout option for the socket.

    – bluuf
    Nov 24 '18 at 13:00


















1















I am trying to write a routine in powershell which will listen on a UDP port, then exit when a key is pressed. The problem I have is that the program will only exit after a datagram has been read.



I.e. It will read n values, user will hit F12, program will wait until it gets the n+1th value, then exit.



What should happen is: reads n values, user will hit F12, program should shut down.



$endpoint = New-Object System.Net.IPEndPoint ([IPAddress]::Any, $port)
$continue = $true
while($continue)
{

if ([console]::KeyAvailable)
{
echo "Exit with F12";
$x = [System.Console]::ReadKey()

switch ( $x.key)
{
F12 { $continue = $false }
}
}
else
{

$socket = New-Object System.Net.Sockets.UdpClient $port
$content = $socket.Receive([ref]$endpoint)
$socket.Close()
[Text.Encoding]::ASCII.GetString($content)
}
}


I'm completely new to Powershell, so maybe this isn't possible. The rest of the code has been stolen from other answers here.










share|improve this question


















  • 1





    The Receive method is blocking : it will halt until a datagram has been received. Either use an async version or set the receivetimout option for the socket.

    – bluuf
    Nov 24 '18 at 13:00














1












1








1


1






I am trying to write a routine in powershell which will listen on a UDP port, then exit when a key is pressed. The problem I have is that the program will only exit after a datagram has been read.



I.e. It will read n values, user will hit F12, program will wait until it gets the n+1th value, then exit.



What should happen is: reads n values, user will hit F12, program should shut down.



$endpoint = New-Object System.Net.IPEndPoint ([IPAddress]::Any, $port)
$continue = $true
while($continue)
{

if ([console]::KeyAvailable)
{
echo "Exit with F12";
$x = [System.Console]::ReadKey()

switch ( $x.key)
{
F12 { $continue = $false }
}
}
else
{

$socket = New-Object System.Net.Sockets.UdpClient $port
$content = $socket.Receive([ref]$endpoint)
$socket.Close()
[Text.Encoding]::ASCII.GetString($content)
}
}


I'm completely new to Powershell, so maybe this isn't possible. The rest of the code has been stolen from other answers here.










share|improve this question














I am trying to write a routine in powershell which will listen on a UDP port, then exit when a key is pressed. The problem I have is that the program will only exit after a datagram has been read.



I.e. It will read n values, user will hit F12, program will wait until it gets the n+1th value, then exit.



What should happen is: reads n values, user will hit F12, program should shut down.



$endpoint = New-Object System.Net.IPEndPoint ([IPAddress]::Any, $port)
$continue = $true
while($continue)
{

if ([console]::KeyAvailable)
{
echo "Exit with F12";
$x = [System.Console]::ReadKey()

switch ( $x.key)
{
F12 { $continue = $false }
}
}
else
{

$socket = New-Object System.Net.Sockets.UdpClient $port
$content = $socket.Receive([ref]$endpoint)
$socket.Close()
[Text.Encoding]::ASCII.GetString($content)
}
}


I'm completely new to Powershell, so maybe this isn't possible. The rest of the code has been stolen from other answers here.







powershell sockets






share|improve this question













share|improve this question











share|improve this question




share|improve this question










asked Nov 24 '18 at 12:22









CluelessUserCluelessUser

82




82








  • 1





    The Receive method is blocking : it will halt until a datagram has been received. Either use an async version or set the receivetimout option for the socket.

    – bluuf
    Nov 24 '18 at 13:00














  • 1





    The Receive method is blocking : it will halt until a datagram has been received. Either use an async version or set the receivetimout option for the socket.

    – bluuf
    Nov 24 '18 at 13:00








1




1





The Receive method is blocking : it will halt until a datagram has been received. Either use an async version or set the receivetimout option for the socket.

– bluuf
Nov 24 '18 at 13:00





The Receive method is blocking : it will halt until a datagram has been received. Either use an async version or set the receivetimout option for the socket.

– bluuf
Nov 24 '18 at 13:00












1 Answer
1






active

oldest

votes


















1














A solution that uses the ReceiveTimeout property, which is mentioned in the @bluuf's comment:



$p = 17042
$e = New-Object System.Net.IPEndPoint ([System.Net.IPAddress]::Any, $p)
$u = New-Object System.Net.Sockets.UdpClient $p
$u.Client.ReceiveTimeout = 100
try
{
for()
{
try
{
$b = $u.Receive([ref]$e)
$s = [System.Text.Encoding]::ASCII.GetString($b)
Write-Host $s
}
catch [System.Net.Sockets.SocketException]
{
if ( $_.Exception.SocketErrorCode -ne 'TimedOut' )
{
throw
}
}
if ( [System.Console]::KeyAvailable )
{
$x = [System.Console]::ReadKey($true)
if ( $x.key -eq [System.ConsoleKey]::F12 )
{
Write-Host 'Exit with F12'
break
}
}
}
}
finally
{
$u.Close()
}


The asynchronous version might look like this:



if( -not('CallbackEventBridge' -as [type]) )
{
Add-Type @'
using System;

public sealed class CallbackEventBridge
{
public event AsyncCallback CallbackComplete = delegate { };

private CallbackEventBridge() {}

private void CallbackInternal(IAsyncResult result)
{
CallbackComplete(result);
}

public AsyncCallback Callback
{
get { return new AsyncCallback(CallbackInternal); }
}

public static CallbackEventBridge Create()
{
return new CallbackEventBridge();
}
}
'@
}
$sb = {
param($ar)
$e = $ar.AsyncState.e
$u = $ar.AsyncState.u
$b = $u.EndReceive($ar, [ref]$e)
$s = [System.Text.Encoding]::ASCII.GetString($b)
Write-Host $s
$ar.AsyncState.completed = $true
}
$bridge = [CallbackEventBridge]::Create()
Register-ObjectEvent -InputObject $bridge -EventName CallbackComplete -Action $sb > $null
$p = 17042
$e = New-Object System.Net.IPEndPoint ([System.Net.IPAddress]::Any, $p)
$u = New-Object System.Net.Sockets.UdpClient $p
$state = @{e = $e; u = $u; completed = $true}
try
{
for()
{
if( $state.completed )
{
$state.completed = $false
[void]$u.BeginReceive($bridge.Callback, $state)
}
if ( [System.Console]::KeyAvailable )
{
$x = [System.Console]::ReadKey($true)
if ( $x.key -eq [System.ConsoleKey]::F12 )
{
Write-Host 'Exit with F12'
break
}
}
[System.Threading.Thread]::Sleep(100)
}
}
finally
{
$u.Close()
}


Learn more about the CallbackEventouBridge class in the PowerShell 2.0 – Asynchronous Callbacks from .NET article by Oisin Grehan.



Both versions can be tested with the following code snippet:



$p = 17042
$u = New-Object System.Net.Sockets.UdpClient
$b = [System.Text.Encoding]::ASCII.GetBytes('Is anybody there')
$u.Connect('localhost', $p)
[void]$u.Send($b, $b.Length)
$u.Close()





share|improve this answer


























    Your Answer






    StackExchange.ifUsing("editor", function () {
    StackExchange.using("externalEditor", function () {
    StackExchange.using("snippets", function () {
    StackExchange.snippets.init();
    });
    });
    }, "code-snippets");

    StackExchange.ready(function() {
    var channelOptions = {
    tags: "".split(" "),
    id: "1"
    };
    initTagRenderer("".split(" "), "".split(" "), channelOptions);

    StackExchange.using("externalEditor", function() {
    // Have to fire editor after snippets, if snippets enabled
    if (StackExchange.settings.snippets.snippetsEnabled) {
    StackExchange.using("snippets", function() {
    createEditor();
    });
    }
    else {
    createEditor();
    }
    });

    function createEditor() {
    StackExchange.prepareEditor({
    heartbeatType: 'answer',
    autoActivateHeartbeat: false,
    convertImagesToLinks: true,
    noModals: true,
    showLowRepImageUploadWarning: true,
    reputationToPostImages: 10,
    bindNavPrevention: true,
    postfix: "",
    imageUploader: {
    brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
    contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
    allowUrls: true
    },
    onDemand: true,
    discardSelector: ".discard-answer"
    ,immediatelyShowMarkdownHelp:true
    });


    }
    });














    draft saved

    draft discarded


















    StackExchange.ready(
    function () {
    StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f53458103%2fexiting-a-udp-listen-routine%23new-answer', 'question_page');
    }
    );

    Post as a guest















    Required, but never shown

























    1 Answer
    1






    active

    oldest

    votes








    1 Answer
    1






    active

    oldest

    votes









    active

    oldest

    votes






    active

    oldest

    votes









    1














    A solution that uses the ReceiveTimeout property, which is mentioned in the @bluuf's comment:



    $p = 17042
    $e = New-Object System.Net.IPEndPoint ([System.Net.IPAddress]::Any, $p)
    $u = New-Object System.Net.Sockets.UdpClient $p
    $u.Client.ReceiveTimeout = 100
    try
    {
    for()
    {
    try
    {
    $b = $u.Receive([ref]$e)
    $s = [System.Text.Encoding]::ASCII.GetString($b)
    Write-Host $s
    }
    catch [System.Net.Sockets.SocketException]
    {
    if ( $_.Exception.SocketErrorCode -ne 'TimedOut' )
    {
    throw
    }
    }
    if ( [System.Console]::KeyAvailable )
    {
    $x = [System.Console]::ReadKey($true)
    if ( $x.key -eq [System.ConsoleKey]::F12 )
    {
    Write-Host 'Exit with F12'
    break
    }
    }
    }
    }
    finally
    {
    $u.Close()
    }


    The asynchronous version might look like this:



    if( -not('CallbackEventBridge' -as [type]) )
    {
    Add-Type @'
    using System;

    public sealed class CallbackEventBridge
    {
    public event AsyncCallback CallbackComplete = delegate { };

    private CallbackEventBridge() {}

    private void CallbackInternal(IAsyncResult result)
    {
    CallbackComplete(result);
    }

    public AsyncCallback Callback
    {
    get { return new AsyncCallback(CallbackInternal); }
    }

    public static CallbackEventBridge Create()
    {
    return new CallbackEventBridge();
    }
    }
    '@
    }
    $sb = {
    param($ar)
    $e = $ar.AsyncState.e
    $u = $ar.AsyncState.u
    $b = $u.EndReceive($ar, [ref]$e)
    $s = [System.Text.Encoding]::ASCII.GetString($b)
    Write-Host $s
    $ar.AsyncState.completed = $true
    }
    $bridge = [CallbackEventBridge]::Create()
    Register-ObjectEvent -InputObject $bridge -EventName CallbackComplete -Action $sb > $null
    $p = 17042
    $e = New-Object System.Net.IPEndPoint ([System.Net.IPAddress]::Any, $p)
    $u = New-Object System.Net.Sockets.UdpClient $p
    $state = @{e = $e; u = $u; completed = $true}
    try
    {
    for()
    {
    if( $state.completed )
    {
    $state.completed = $false
    [void]$u.BeginReceive($bridge.Callback, $state)
    }
    if ( [System.Console]::KeyAvailable )
    {
    $x = [System.Console]::ReadKey($true)
    if ( $x.key -eq [System.ConsoleKey]::F12 )
    {
    Write-Host 'Exit with F12'
    break
    }
    }
    [System.Threading.Thread]::Sleep(100)
    }
    }
    finally
    {
    $u.Close()
    }


    Learn more about the CallbackEventouBridge class in the PowerShell 2.0 – Asynchronous Callbacks from .NET article by Oisin Grehan.



    Both versions can be tested with the following code snippet:



    $p = 17042
    $u = New-Object System.Net.Sockets.UdpClient
    $b = [System.Text.Encoding]::ASCII.GetBytes('Is anybody there')
    $u.Connect('localhost', $p)
    [void]$u.Send($b, $b.Length)
    $u.Close()





    share|improve this answer






























      1














      A solution that uses the ReceiveTimeout property, which is mentioned in the @bluuf's comment:



      $p = 17042
      $e = New-Object System.Net.IPEndPoint ([System.Net.IPAddress]::Any, $p)
      $u = New-Object System.Net.Sockets.UdpClient $p
      $u.Client.ReceiveTimeout = 100
      try
      {
      for()
      {
      try
      {
      $b = $u.Receive([ref]$e)
      $s = [System.Text.Encoding]::ASCII.GetString($b)
      Write-Host $s
      }
      catch [System.Net.Sockets.SocketException]
      {
      if ( $_.Exception.SocketErrorCode -ne 'TimedOut' )
      {
      throw
      }
      }
      if ( [System.Console]::KeyAvailable )
      {
      $x = [System.Console]::ReadKey($true)
      if ( $x.key -eq [System.ConsoleKey]::F12 )
      {
      Write-Host 'Exit with F12'
      break
      }
      }
      }
      }
      finally
      {
      $u.Close()
      }


      The asynchronous version might look like this:



      if( -not('CallbackEventBridge' -as [type]) )
      {
      Add-Type @'
      using System;

      public sealed class CallbackEventBridge
      {
      public event AsyncCallback CallbackComplete = delegate { };

      private CallbackEventBridge() {}

      private void CallbackInternal(IAsyncResult result)
      {
      CallbackComplete(result);
      }

      public AsyncCallback Callback
      {
      get { return new AsyncCallback(CallbackInternal); }
      }

      public static CallbackEventBridge Create()
      {
      return new CallbackEventBridge();
      }
      }
      '@
      }
      $sb = {
      param($ar)
      $e = $ar.AsyncState.e
      $u = $ar.AsyncState.u
      $b = $u.EndReceive($ar, [ref]$e)
      $s = [System.Text.Encoding]::ASCII.GetString($b)
      Write-Host $s
      $ar.AsyncState.completed = $true
      }
      $bridge = [CallbackEventBridge]::Create()
      Register-ObjectEvent -InputObject $bridge -EventName CallbackComplete -Action $sb > $null
      $p = 17042
      $e = New-Object System.Net.IPEndPoint ([System.Net.IPAddress]::Any, $p)
      $u = New-Object System.Net.Sockets.UdpClient $p
      $state = @{e = $e; u = $u; completed = $true}
      try
      {
      for()
      {
      if( $state.completed )
      {
      $state.completed = $false
      [void]$u.BeginReceive($bridge.Callback, $state)
      }
      if ( [System.Console]::KeyAvailable )
      {
      $x = [System.Console]::ReadKey($true)
      if ( $x.key -eq [System.ConsoleKey]::F12 )
      {
      Write-Host 'Exit with F12'
      break
      }
      }
      [System.Threading.Thread]::Sleep(100)
      }
      }
      finally
      {
      $u.Close()
      }


      Learn more about the CallbackEventouBridge class in the PowerShell 2.0 – Asynchronous Callbacks from .NET article by Oisin Grehan.



      Both versions can be tested with the following code snippet:



      $p = 17042
      $u = New-Object System.Net.Sockets.UdpClient
      $b = [System.Text.Encoding]::ASCII.GetBytes('Is anybody there')
      $u.Connect('localhost', $p)
      [void]$u.Send($b, $b.Length)
      $u.Close()





      share|improve this answer




























        1












        1








        1







        A solution that uses the ReceiveTimeout property, which is mentioned in the @bluuf's comment:



        $p = 17042
        $e = New-Object System.Net.IPEndPoint ([System.Net.IPAddress]::Any, $p)
        $u = New-Object System.Net.Sockets.UdpClient $p
        $u.Client.ReceiveTimeout = 100
        try
        {
        for()
        {
        try
        {
        $b = $u.Receive([ref]$e)
        $s = [System.Text.Encoding]::ASCII.GetString($b)
        Write-Host $s
        }
        catch [System.Net.Sockets.SocketException]
        {
        if ( $_.Exception.SocketErrorCode -ne 'TimedOut' )
        {
        throw
        }
        }
        if ( [System.Console]::KeyAvailable )
        {
        $x = [System.Console]::ReadKey($true)
        if ( $x.key -eq [System.ConsoleKey]::F12 )
        {
        Write-Host 'Exit with F12'
        break
        }
        }
        }
        }
        finally
        {
        $u.Close()
        }


        The asynchronous version might look like this:



        if( -not('CallbackEventBridge' -as [type]) )
        {
        Add-Type @'
        using System;

        public sealed class CallbackEventBridge
        {
        public event AsyncCallback CallbackComplete = delegate { };

        private CallbackEventBridge() {}

        private void CallbackInternal(IAsyncResult result)
        {
        CallbackComplete(result);
        }

        public AsyncCallback Callback
        {
        get { return new AsyncCallback(CallbackInternal); }
        }

        public static CallbackEventBridge Create()
        {
        return new CallbackEventBridge();
        }
        }
        '@
        }
        $sb = {
        param($ar)
        $e = $ar.AsyncState.e
        $u = $ar.AsyncState.u
        $b = $u.EndReceive($ar, [ref]$e)
        $s = [System.Text.Encoding]::ASCII.GetString($b)
        Write-Host $s
        $ar.AsyncState.completed = $true
        }
        $bridge = [CallbackEventBridge]::Create()
        Register-ObjectEvent -InputObject $bridge -EventName CallbackComplete -Action $sb > $null
        $p = 17042
        $e = New-Object System.Net.IPEndPoint ([System.Net.IPAddress]::Any, $p)
        $u = New-Object System.Net.Sockets.UdpClient $p
        $state = @{e = $e; u = $u; completed = $true}
        try
        {
        for()
        {
        if( $state.completed )
        {
        $state.completed = $false
        [void]$u.BeginReceive($bridge.Callback, $state)
        }
        if ( [System.Console]::KeyAvailable )
        {
        $x = [System.Console]::ReadKey($true)
        if ( $x.key -eq [System.ConsoleKey]::F12 )
        {
        Write-Host 'Exit with F12'
        break
        }
        }
        [System.Threading.Thread]::Sleep(100)
        }
        }
        finally
        {
        $u.Close()
        }


        Learn more about the CallbackEventouBridge class in the PowerShell 2.0 – Asynchronous Callbacks from .NET article by Oisin Grehan.



        Both versions can be tested with the following code snippet:



        $p = 17042
        $u = New-Object System.Net.Sockets.UdpClient
        $b = [System.Text.Encoding]::ASCII.GetBytes('Is anybody there')
        $u.Connect('localhost', $p)
        [void]$u.Send($b, $b.Length)
        $u.Close()





        share|improve this answer















        A solution that uses the ReceiveTimeout property, which is mentioned in the @bluuf's comment:



        $p = 17042
        $e = New-Object System.Net.IPEndPoint ([System.Net.IPAddress]::Any, $p)
        $u = New-Object System.Net.Sockets.UdpClient $p
        $u.Client.ReceiveTimeout = 100
        try
        {
        for()
        {
        try
        {
        $b = $u.Receive([ref]$e)
        $s = [System.Text.Encoding]::ASCII.GetString($b)
        Write-Host $s
        }
        catch [System.Net.Sockets.SocketException]
        {
        if ( $_.Exception.SocketErrorCode -ne 'TimedOut' )
        {
        throw
        }
        }
        if ( [System.Console]::KeyAvailable )
        {
        $x = [System.Console]::ReadKey($true)
        if ( $x.key -eq [System.ConsoleKey]::F12 )
        {
        Write-Host 'Exit with F12'
        break
        }
        }
        }
        }
        finally
        {
        $u.Close()
        }


        The asynchronous version might look like this:



        if( -not('CallbackEventBridge' -as [type]) )
        {
        Add-Type @'
        using System;

        public sealed class CallbackEventBridge
        {
        public event AsyncCallback CallbackComplete = delegate { };

        private CallbackEventBridge() {}

        private void CallbackInternal(IAsyncResult result)
        {
        CallbackComplete(result);
        }

        public AsyncCallback Callback
        {
        get { return new AsyncCallback(CallbackInternal); }
        }

        public static CallbackEventBridge Create()
        {
        return new CallbackEventBridge();
        }
        }
        '@
        }
        $sb = {
        param($ar)
        $e = $ar.AsyncState.e
        $u = $ar.AsyncState.u
        $b = $u.EndReceive($ar, [ref]$e)
        $s = [System.Text.Encoding]::ASCII.GetString($b)
        Write-Host $s
        $ar.AsyncState.completed = $true
        }
        $bridge = [CallbackEventBridge]::Create()
        Register-ObjectEvent -InputObject $bridge -EventName CallbackComplete -Action $sb > $null
        $p = 17042
        $e = New-Object System.Net.IPEndPoint ([System.Net.IPAddress]::Any, $p)
        $u = New-Object System.Net.Sockets.UdpClient $p
        $state = @{e = $e; u = $u; completed = $true}
        try
        {
        for()
        {
        if( $state.completed )
        {
        $state.completed = $false
        [void]$u.BeginReceive($bridge.Callback, $state)
        }
        if ( [System.Console]::KeyAvailable )
        {
        $x = [System.Console]::ReadKey($true)
        if ( $x.key -eq [System.ConsoleKey]::F12 )
        {
        Write-Host 'Exit with F12'
        break
        }
        }
        [System.Threading.Thread]::Sleep(100)
        }
        }
        finally
        {
        $u.Close()
        }


        Learn more about the CallbackEventouBridge class in the PowerShell 2.0 – Asynchronous Callbacks from .NET article by Oisin Grehan.



        Both versions can be tested with the following code snippet:



        $p = 17042
        $u = New-Object System.Net.Sockets.UdpClient
        $b = [System.Text.Encoding]::ASCII.GetBytes('Is anybody there')
        $u.Connect('localhost', $p)
        [void]$u.Send($b, $b.Length)
        $u.Close()






        share|improve this answer














        share|improve this answer



        share|improve this answer








        edited Nov 26 '18 at 8:03

























        answered Nov 25 '18 at 6:00









        Andrei OdegovAndrei Odegov

        1,62311016




        1,62311016
































            draft saved

            draft discarded




















































            Thanks for contributing an answer to Stack Overflow!


            • Please be sure to answer the question. Provide details and share your research!

            But avoid



            • Asking for help, clarification, or responding to other answers.

            • Making statements based on opinion; back them up with references or personal experience.


            To learn more, see our tips on writing great answers.




            draft saved


            draft discarded














            StackExchange.ready(
            function () {
            StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f53458103%2fexiting-a-udp-listen-routine%23new-answer', 'question_page');
            }
            );

            Post as a guest















            Required, but never shown





















































            Required, but never shown














            Required, but never shown












            Required, but never shown







            Required, but never shown

































            Required, but never shown














            Required, but never shown












            Required, but never shown







            Required, but never shown







            這個網誌中的熱門文章

            Tangent Lines Diagram Along Smooth Curve

            Yusuf al-Mu'taman ibn Hud

            Zucchini