how to stop reading when not expecting any message












1














in the below code we asynchronously wait to receive data. But how to stop waiting for read when not expecting anymore data.
The reason I'm asking this is because I want to implement a class which keeps listening to arriving messages in a separate thread using asyncio.run_coroutine_threadsafe and want to terminate listening once my test gets over (in order to release socket connection).



import asyncio

@asyncio.coroutine
def tcp_echo_client(message, loop):
reader, writer = yield from asyncio.open_connection('127.0.0.1', 8888,
loop=loop)

print('Send: %r' % message)
writer.write(message.encode())

data = yield from reader.read(100)
print('Received: %r' % data.decode())

print('Close the socket')
writer.close()

message = 'Hello World!'
loop = asyncio.get_event_loop()
loop.run_until_complete(tcp_echo_client(message, loop))
loop.close()









share|improve this question



























    1














    in the below code we asynchronously wait to receive data. But how to stop waiting for read when not expecting anymore data.
    The reason I'm asking this is because I want to implement a class which keeps listening to arriving messages in a separate thread using asyncio.run_coroutine_threadsafe and want to terminate listening once my test gets over (in order to release socket connection).



    import asyncio

    @asyncio.coroutine
    def tcp_echo_client(message, loop):
    reader, writer = yield from asyncio.open_connection('127.0.0.1', 8888,
    loop=loop)

    print('Send: %r' % message)
    writer.write(message.encode())

    data = yield from reader.read(100)
    print('Received: %r' % data.decode())

    print('Close the socket')
    writer.close()

    message = 'Hello World!'
    loop = asyncio.get_event_loop()
    loop.run_until_complete(tcp_echo_client(message, loop))
    loop.close()









    share|improve this question

























      1












      1








      1







      in the below code we asynchronously wait to receive data. But how to stop waiting for read when not expecting anymore data.
      The reason I'm asking this is because I want to implement a class which keeps listening to arriving messages in a separate thread using asyncio.run_coroutine_threadsafe and want to terminate listening once my test gets over (in order to release socket connection).



      import asyncio

      @asyncio.coroutine
      def tcp_echo_client(message, loop):
      reader, writer = yield from asyncio.open_connection('127.0.0.1', 8888,
      loop=loop)

      print('Send: %r' % message)
      writer.write(message.encode())

      data = yield from reader.read(100)
      print('Received: %r' % data.decode())

      print('Close the socket')
      writer.close()

      message = 'Hello World!'
      loop = asyncio.get_event_loop()
      loop.run_until_complete(tcp_echo_client(message, loop))
      loop.close()









      share|improve this question













      in the below code we asynchronously wait to receive data. But how to stop waiting for read when not expecting anymore data.
      The reason I'm asking this is because I want to implement a class which keeps listening to arriving messages in a separate thread using asyncio.run_coroutine_threadsafe and want to terminate listening once my test gets over (in order to release socket connection).



      import asyncio

      @asyncio.coroutine
      def tcp_echo_client(message, loop):
      reader, writer = yield from asyncio.open_connection('127.0.0.1', 8888,
      loop=loop)

      print('Send: %r' % message)
      writer.write(message.encode())

      data = yield from reader.read(100)
      print('Received: %r' % data.decode())

      print('Close the socket')
      writer.close()

      message = 'Hello World!'
      loop = asyncio.get_event_loop()
      loop.run_until_complete(tcp_echo_client(message, loop))
      loop.close()






      python python-3.4 python-asyncio






      share|improve this question













      share|improve this question











      share|improve this question




      share|improve this question










      asked Nov 13 '18 at 6:08









      sandeepsandeep

      165




      165
























          2 Answers
          2






          active

          oldest

          votes


















          0














          To stop waiting, cancel the task that runs the coroutine. For example:



          # tcp_echo_client as in your code

          message = 'Hello World!'
          loop = asyncio.get_event_loop()
          task = loop.create_task(tcp_echo_client(message, loop))
          loop.call_later(5, task.cancel) # cancel the task after five seconds
          try:
          loop.run_until_complete(task)
          except asyncio.CancelledError:
          pass
          loop.close()


          If you are using asyncio.run_coroutine_threadsafe, note that it returns a concurrent.futures.Future object, which itself has a cancel method. Cancellation of the future returned by run_coroutine_threadsafe will be noticed by asyncio and result in the cancellation of the task in the event loop thread.






          share|improve this answer





























            0














            streamreader doesn't comes with any timeout https://github.com/python/asyncio/issues/96
            so once you start reading you cannot stop.
            For me I sent a closing message and handled in my client that on encountering closing message it should not go for further read.
            That's how i stopped reading.
            Once reader.read is called it keeps waiting for a message (Even after calling writer.close) and keeps the socket engaged until object is destroyed.






            share|improve this answer





















            • It is not true that once you start reading you cannot stop. For example, you can use data = await asyncio.wait_for(reader.read(4096), 5), and reading will time out in 5 seconds.
              – user4815162342
              Nov 23 '18 at 23:28













            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%2f53274805%2fhow-to-stop-reading-when-not-expecting-any-message%23new-answer', 'question_page');
            }
            );

            Post as a guest















            Required, but never shown

























            2 Answers
            2






            active

            oldest

            votes








            2 Answers
            2






            active

            oldest

            votes









            active

            oldest

            votes






            active

            oldest

            votes









            0














            To stop waiting, cancel the task that runs the coroutine. For example:



            # tcp_echo_client as in your code

            message = 'Hello World!'
            loop = asyncio.get_event_loop()
            task = loop.create_task(tcp_echo_client(message, loop))
            loop.call_later(5, task.cancel) # cancel the task after five seconds
            try:
            loop.run_until_complete(task)
            except asyncio.CancelledError:
            pass
            loop.close()


            If you are using asyncio.run_coroutine_threadsafe, note that it returns a concurrent.futures.Future object, which itself has a cancel method. Cancellation of the future returned by run_coroutine_threadsafe will be noticed by asyncio and result in the cancellation of the task in the event loop thread.






            share|improve this answer


























              0














              To stop waiting, cancel the task that runs the coroutine. For example:



              # tcp_echo_client as in your code

              message = 'Hello World!'
              loop = asyncio.get_event_loop()
              task = loop.create_task(tcp_echo_client(message, loop))
              loop.call_later(5, task.cancel) # cancel the task after five seconds
              try:
              loop.run_until_complete(task)
              except asyncio.CancelledError:
              pass
              loop.close()


              If you are using asyncio.run_coroutine_threadsafe, note that it returns a concurrent.futures.Future object, which itself has a cancel method. Cancellation of the future returned by run_coroutine_threadsafe will be noticed by asyncio and result in the cancellation of the task in the event loop thread.






              share|improve this answer
























                0












                0








                0






                To stop waiting, cancel the task that runs the coroutine. For example:



                # tcp_echo_client as in your code

                message = 'Hello World!'
                loop = asyncio.get_event_loop()
                task = loop.create_task(tcp_echo_client(message, loop))
                loop.call_later(5, task.cancel) # cancel the task after five seconds
                try:
                loop.run_until_complete(task)
                except asyncio.CancelledError:
                pass
                loop.close()


                If you are using asyncio.run_coroutine_threadsafe, note that it returns a concurrent.futures.Future object, which itself has a cancel method. Cancellation of the future returned by run_coroutine_threadsafe will be noticed by asyncio and result in the cancellation of the task in the event loop thread.






                share|improve this answer












                To stop waiting, cancel the task that runs the coroutine. For example:



                # tcp_echo_client as in your code

                message = 'Hello World!'
                loop = asyncio.get_event_loop()
                task = loop.create_task(tcp_echo_client(message, loop))
                loop.call_later(5, task.cancel) # cancel the task after five seconds
                try:
                loop.run_until_complete(task)
                except asyncio.CancelledError:
                pass
                loop.close()


                If you are using asyncio.run_coroutine_threadsafe, note that it returns a concurrent.futures.Future object, which itself has a cancel method. Cancellation of the future returned by run_coroutine_threadsafe will be noticed by asyncio and result in the cancellation of the task in the event loop thread.







                share|improve this answer












                share|improve this answer



                share|improve this answer










                answered Nov 13 '18 at 12:48









                user4815162342user4815162342

                61k590141




                61k590141

























                    0














                    streamreader doesn't comes with any timeout https://github.com/python/asyncio/issues/96
                    so once you start reading you cannot stop.
                    For me I sent a closing message and handled in my client that on encountering closing message it should not go for further read.
                    That's how i stopped reading.
                    Once reader.read is called it keeps waiting for a message (Even after calling writer.close) and keeps the socket engaged until object is destroyed.






                    share|improve this answer





















                    • It is not true that once you start reading you cannot stop. For example, you can use data = await asyncio.wait_for(reader.read(4096), 5), and reading will time out in 5 seconds.
                      – user4815162342
                      Nov 23 '18 at 23:28


















                    0














                    streamreader doesn't comes with any timeout https://github.com/python/asyncio/issues/96
                    so once you start reading you cannot stop.
                    For me I sent a closing message and handled in my client that on encountering closing message it should not go for further read.
                    That's how i stopped reading.
                    Once reader.read is called it keeps waiting for a message (Even after calling writer.close) and keeps the socket engaged until object is destroyed.






                    share|improve this answer





















                    • It is not true that once you start reading you cannot stop. For example, you can use data = await asyncio.wait_for(reader.read(4096), 5), and reading will time out in 5 seconds.
                      – user4815162342
                      Nov 23 '18 at 23:28
















                    0












                    0








                    0






                    streamreader doesn't comes with any timeout https://github.com/python/asyncio/issues/96
                    so once you start reading you cannot stop.
                    For me I sent a closing message and handled in my client that on encountering closing message it should not go for further read.
                    That's how i stopped reading.
                    Once reader.read is called it keeps waiting for a message (Even after calling writer.close) and keeps the socket engaged until object is destroyed.






                    share|improve this answer












                    streamreader doesn't comes with any timeout https://github.com/python/asyncio/issues/96
                    so once you start reading you cannot stop.
                    For me I sent a closing message and handled in my client that on encountering closing message it should not go for further read.
                    That's how i stopped reading.
                    Once reader.read is called it keeps waiting for a message (Even after calling writer.close) and keeps the socket engaged until object is destroyed.







                    share|improve this answer












                    share|improve this answer



                    share|improve this answer










                    answered Nov 19 '18 at 6:32









                    sandeepsandeep

                    165




                    165












                    • It is not true that once you start reading you cannot stop. For example, you can use data = await asyncio.wait_for(reader.read(4096), 5), and reading will time out in 5 seconds.
                      – user4815162342
                      Nov 23 '18 at 23:28




















                    • It is not true that once you start reading you cannot stop. For example, you can use data = await asyncio.wait_for(reader.read(4096), 5), and reading will time out in 5 seconds.
                      – user4815162342
                      Nov 23 '18 at 23:28


















                    It is not true that once you start reading you cannot stop. For example, you can use data = await asyncio.wait_for(reader.read(4096), 5), and reading will time out in 5 seconds.
                    – user4815162342
                    Nov 23 '18 at 23:28






                    It is not true that once you start reading you cannot stop. For example, you can use data = await asyncio.wait_for(reader.read(4096), 5), and reading will time out in 5 seconds.
                    – user4815162342
                    Nov 23 '18 at 23:28




















                    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%2f53274805%2fhow-to-stop-reading-when-not-expecting-any-message%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







                    這個網誌中的熱門文章

                    Xamarin.form Move up view when keyboard appear

                    Post-Redirect-Get with Spring WebFlux and Thymeleaf

                    Anylogic : not able to use stopDelay()