Simple Chat asyncio.Protocol, saving data from transport stream into fileDownload file from web in Python 3Simple Python Webserver to save fileasyncio streams check if reader has dataTkInter Frame doesn't load if another function is calledWhat is the correct way to yield from a stream?async / await: Continuously stream data from async methodWhat is the obvious way of making a simple async socket chat server in Python 3?python asyncronous images download (multiple urls)Click a download link with Python and Selenium's Firefox WebdriverPython - Streaming data from file to asyncio-enabled Kinesis Producer

Do the books ever say oliphaunts aren’t elephants?

Piece of chess engine, which accomplishes move generation

A variant of the Multiple Traveling Salesman Problem

Is it possible for a particle to decay via gravity?

What clothes would flying-people wear?

Why did I lose on time with 3 pawns vs Knight. Shouldn't it be a draw?

Why would an invisible personal shield be necessary?

Why did some Apollo missions carry a grenade launcher?

Narset, Parter of Veils interaction with Aria of Flame

How to efficiently shred a lot of cabbage?

Story about separate individuals coming together to make some supernatural universe power

Should I intervene when a colleague in a different department makes students run laps as part of their grade?

Convert graph format for Mathematica graph functions

Is there a word to describe someone who is, or the state of being, content with hanging around others without interacting with them?

Why tantalum for the Hayabusa bullets?

If you inherit a Roth 401(k), is it taxed?

How to season a character?

Why does Canada require bilingualism in a lot of federal government posts?

What Marvel character has this 'W' symbol?

Why force the nose of 737 Max down in the first place?

Is it unprofessional to mention your cover letter and resume are best viewed in Chrome?

Would people understand me speaking German all over Europe?

Should I accept an invitation to give a talk from someone who might review my proposal?

Is it safe if the neutral lead is exposed and disconnected?



Simple Chat asyncio.Protocol, saving data from transport stream into file


Download file from web in Python 3Simple Python Webserver to save fileasyncio streams check if reader has dataTkInter Frame doesn't load if another function is calledWhat is the correct way to yield from a stream?async / await: Continuously stream data from async methodWhat is the obvious way of making a simple async socket chat server in Python 3?python asyncronous images download (multiple urls)Click a download link with Python and Selenium's Firefox WebdriverPython - Streaming data from file to asyncio-enabled Kinesis Producer






.everyoneloves__top-leaderboard:empty,.everyoneloves__mid-leaderboard:empty,.everyoneloves__bot-mid-leaderboard:empty margin-bottom:0;








0















I am making simple asyncio.Protocol Server-Client chat. What left to do is save chat history so every new client after set nickname get chat history.



I have no idea how to avoid duplicating messages in data stream. I tried to capture what is displayed in the server instance to a file. I did not have this problem in the version with sockets and treads.
Something eludes me and it is definitely a cliché.



CLIENT.py



import asyncio
import threading
import socket
import sServer
import random

class Client(asyncio.Protocol):
def __init__(self):
self.name = None

def connection_made(self, transport):
self.name = set_nickname()
print("Type your message below or 'EXIT' to quit")
self.transport = transport
try:
with open('history.txt', 'rt') as history:
content = history.read()
print(content)
except FileNotFoundError:
pass

transport.write(('USR:'+self.name).encode())
thread = threading.Thread(target=self.handle_input, daemon=True)
thread.start()


def data_received(self, data):
print(data.decode())

def eof_received(self):
print("Connection lost...")

def connection_lost(self, exc):
self.transport.close()

def handle_input(self):
while True:
message = input('ME> ')
if message == 'EXIT':
self.transport.write(message.encode())

# elif message == 'HIST':
# self.load_history()

else:
self.transport.write(('MSG:'+message).encode())


def set_nickname():
try:
#user = 'hardcoded'
print("Type your nickname: ")
user = input().strip()
print("Hello ".format(user))
client_name = socket.gethostname()
ip = socket.gethostbyname(client_name)
# create random n
rest = random.randrange(1, 100, 1)
# for local purpose and testing multiply clients
client_ip = "@-".format(ip, str(rest))
user = user + client_ip
return user
except:
pass


def main():

loop = asyncio.get_event_loop()
coroutine = loop.create_connection(Client, sServer.HOST, sServer.PORT)
loop.run_until_complete(coroutine)
loop.run_forever()
loop.close()


if __name__ == "__main__":
main()


SERVER.py



import asyncio
import json
import sys
import os.path

HOST = '127.0.0.1'
PORT = 6666
active_users = []
history =


class Server(asyncio.Protocol):
""" Overriding Protocol methods:
connection_made
data_received
connection_lost
"""
def connection_made(self, transport):
self.transport = transport
self.address = transport.get_extra_info('peername')
print('Connection from '.format(self.address))

def data_received(self, data):
stream = data.decode()

if stream.startswith("USR:"):
self.username = stream[4:]
add_user(self)

elif stream.startswith("MSG:"):
msg = stream[4:]
receive_message((self.username + ': ' + msg), self)
#update_history((self.username + ': ' + msg), self)

history.update(self.username: msg)
with open('history.txt', 'a+') as sample:
for save in [history]:
sample.write('n'.format(save))

elif stream == 'EXIT':
remove_user(self)
self.transport.close()

def add_user(user):
active_users.append(user)
receive_message(user.username + ' has joined!', user)


def remove_user(user):
active_users.remove(user)
receive_message(user.username + ' has left.', user)

def receive_message(msg, author):
print(msg)
for user in active_users:
# don't show user's own messages in session
if user is not author:
user.transport.write(msg.encode())


def main():
loop = asyncio.get_event_loop()
coroutine = loop.create_server(Server, HOST, PORT)
server = loop.run_until_complete(coroutine)
print('Server established on '.format(server.sockets[0].getsockname()))

try:
loop.run_forever()
except KeyboardInterrupt:
if os.path.exists('history.txt'):
try:
os.remove('history.txt')
sys.exit()
except OSError:
pass
finally:
server.close()
loop.close()


if __name__ == '__main__':
main()









share|improve this question






























    0















    I am making simple asyncio.Protocol Server-Client chat. What left to do is save chat history so every new client after set nickname get chat history.



    I have no idea how to avoid duplicating messages in data stream. I tried to capture what is displayed in the server instance to a file. I did not have this problem in the version with sockets and treads.
    Something eludes me and it is definitely a cliché.



    CLIENT.py



    import asyncio
    import threading
    import socket
    import sServer
    import random

    class Client(asyncio.Protocol):
    def __init__(self):
    self.name = None

    def connection_made(self, transport):
    self.name = set_nickname()
    print("Type your message below or 'EXIT' to quit")
    self.transport = transport
    try:
    with open('history.txt', 'rt') as history:
    content = history.read()
    print(content)
    except FileNotFoundError:
    pass

    transport.write(('USR:'+self.name).encode())
    thread = threading.Thread(target=self.handle_input, daemon=True)
    thread.start()


    def data_received(self, data):
    print(data.decode())

    def eof_received(self):
    print("Connection lost...")

    def connection_lost(self, exc):
    self.transport.close()

    def handle_input(self):
    while True:
    message = input('ME> ')
    if message == 'EXIT':
    self.transport.write(message.encode())

    # elif message == 'HIST':
    # self.load_history()

    else:
    self.transport.write(('MSG:'+message).encode())


    def set_nickname():
    try:
    #user = 'hardcoded'
    print("Type your nickname: ")
    user = input().strip()
    print("Hello ".format(user))
    client_name = socket.gethostname()
    ip = socket.gethostbyname(client_name)
    # create random n
    rest = random.randrange(1, 100, 1)
    # for local purpose and testing multiply clients
    client_ip = "@-".format(ip, str(rest))
    user = user + client_ip
    return user
    except:
    pass


    def main():

    loop = asyncio.get_event_loop()
    coroutine = loop.create_connection(Client, sServer.HOST, sServer.PORT)
    loop.run_until_complete(coroutine)
    loop.run_forever()
    loop.close()


    if __name__ == "__main__":
    main()


    SERVER.py



    import asyncio
    import json
    import sys
    import os.path

    HOST = '127.0.0.1'
    PORT = 6666
    active_users = []
    history =


    class Server(asyncio.Protocol):
    """ Overriding Protocol methods:
    connection_made
    data_received
    connection_lost
    """
    def connection_made(self, transport):
    self.transport = transport
    self.address = transport.get_extra_info('peername')
    print('Connection from '.format(self.address))

    def data_received(self, data):
    stream = data.decode()

    if stream.startswith("USR:"):
    self.username = stream[4:]
    add_user(self)

    elif stream.startswith("MSG:"):
    msg = stream[4:]
    receive_message((self.username + ': ' + msg), self)
    #update_history((self.username + ': ' + msg), self)

    history.update(self.username: msg)
    with open('history.txt', 'a+') as sample:
    for save in [history]:
    sample.write('n'.format(save))

    elif stream == 'EXIT':
    remove_user(self)
    self.transport.close()

    def add_user(user):
    active_users.append(user)
    receive_message(user.username + ' has joined!', user)


    def remove_user(user):
    active_users.remove(user)
    receive_message(user.username + ' has left.', user)

    def receive_message(msg, author):
    print(msg)
    for user in active_users:
    # don't show user's own messages in session
    if user is not author:
    user.transport.write(msg.encode())


    def main():
    loop = asyncio.get_event_loop()
    coroutine = loop.create_server(Server, HOST, PORT)
    server = loop.run_until_complete(coroutine)
    print('Server established on '.format(server.sockets[0].getsockname()))

    try:
    loop.run_forever()
    except KeyboardInterrupt:
    if os.path.exists('history.txt'):
    try:
    os.remove('history.txt')
    sys.exit()
    except OSError:
    pass
    finally:
    server.close()
    loop.close()


    if __name__ == '__main__':
    main()









    share|improve this question


























      0












      0








      0


      1






      I am making simple asyncio.Protocol Server-Client chat. What left to do is save chat history so every new client after set nickname get chat history.



      I have no idea how to avoid duplicating messages in data stream. I tried to capture what is displayed in the server instance to a file. I did not have this problem in the version with sockets and treads.
      Something eludes me and it is definitely a cliché.



      CLIENT.py



      import asyncio
      import threading
      import socket
      import sServer
      import random

      class Client(asyncio.Protocol):
      def __init__(self):
      self.name = None

      def connection_made(self, transport):
      self.name = set_nickname()
      print("Type your message below or 'EXIT' to quit")
      self.transport = transport
      try:
      with open('history.txt', 'rt') as history:
      content = history.read()
      print(content)
      except FileNotFoundError:
      pass

      transport.write(('USR:'+self.name).encode())
      thread = threading.Thread(target=self.handle_input, daemon=True)
      thread.start()


      def data_received(self, data):
      print(data.decode())

      def eof_received(self):
      print("Connection lost...")

      def connection_lost(self, exc):
      self.transport.close()

      def handle_input(self):
      while True:
      message = input('ME> ')
      if message == 'EXIT':
      self.transport.write(message.encode())

      # elif message == 'HIST':
      # self.load_history()

      else:
      self.transport.write(('MSG:'+message).encode())


      def set_nickname():
      try:
      #user = 'hardcoded'
      print("Type your nickname: ")
      user = input().strip()
      print("Hello ".format(user))
      client_name = socket.gethostname()
      ip = socket.gethostbyname(client_name)
      # create random n
      rest = random.randrange(1, 100, 1)
      # for local purpose and testing multiply clients
      client_ip = "@-".format(ip, str(rest))
      user = user + client_ip
      return user
      except:
      pass


      def main():

      loop = asyncio.get_event_loop()
      coroutine = loop.create_connection(Client, sServer.HOST, sServer.PORT)
      loop.run_until_complete(coroutine)
      loop.run_forever()
      loop.close()


      if __name__ == "__main__":
      main()


      SERVER.py



      import asyncio
      import json
      import sys
      import os.path

      HOST = '127.0.0.1'
      PORT = 6666
      active_users = []
      history =


      class Server(asyncio.Protocol):
      """ Overriding Protocol methods:
      connection_made
      data_received
      connection_lost
      """
      def connection_made(self, transport):
      self.transport = transport
      self.address = transport.get_extra_info('peername')
      print('Connection from '.format(self.address))

      def data_received(self, data):
      stream = data.decode()

      if stream.startswith("USR:"):
      self.username = stream[4:]
      add_user(self)

      elif stream.startswith("MSG:"):
      msg = stream[4:]
      receive_message((self.username + ': ' + msg), self)
      #update_history((self.username + ': ' + msg), self)

      history.update(self.username: msg)
      with open('history.txt', 'a+') as sample:
      for save in [history]:
      sample.write('n'.format(save))

      elif stream == 'EXIT':
      remove_user(self)
      self.transport.close()

      def add_user(user):
      active_users.append(user)
      receive_message(user.username + ' has joined!', user)


      def remove_user(user):
      active_users.remove(user)
      receive_message(user.username + ' has left.', user)

      def receive_message(msg, author):
      print(msg)
      for user in active_users:
      # don't show user's own messages in session
      if user is not author:
      user.transport.write(msg.encode())


      def main():
      loop = asyncio.get_event_loop()
      coroutine = loop.create_server(Server, HOST, PORT)
      server = loop.run_until_complete(coroutine)
      print('Server established on '.format(server.sockets[0].getsockname()))

      try:
      loop.run_forever()
      except KeyboardInterrupt:
      if os.path.exists('history.txt'):
      try:
      os.remove('history.txt')
      sys.exit()
      except OSError:
      pass
      finally:
      server.close()
      loop.close()


      if __name__ == '__main__':
      main()









      share|improve this question














      I am making simple asyncio.Protocol Server-Client chat. What left to do is save chat history so every new client after set nickname get chat history.



      I have no idea how to avoid duplicating messages in data stream. I tried to capture what is displayed in the server instance to a file. I did not have this problem in the version with sockets and treads.
      Something eludes me and it is definitely a cliché.



      CLIENT.py



      import asyncio
      import threading
      import socket
      import sServer
      import random

      class Client(asyncio.Protocol):
      def __init__(self):
      self.name = None

      def connection_made(self, transport):
      self.name = set_nickname()
      print("Type your message below or 'EXIT' to quit")
      self.transport = transport
      try:
      with open('history.txt', 'rt') as history:
      content = history.read()
      print(content)
      except FileNotFoundError:
      pass

      transport.write(('USR:'+self.name).encode())
      thread = threading.Thread(target=self.handle_input, daemon=True)
      thread.start()


      def data_received(self, data):
      print(data.decode())

      def eof_received(self):
      print("Connection lost...")

      def connection_lost(self, exc):
      self.transport.close()

      def handle_input(self):
      while True:
      message = input('ME> ')
      if message == 'EXIT':
      self.transport.write(message.encode())

      # elif message == 'HIST':
      # self.load_history()

      else:
      self.transport.write(('MSG:'+message).encode())


      def set_nickname():
      try:
      #user = 'hardcoded'
      print("Type your nickname: ")
      user = input().strip()
      print("Hello ".format(user))
      client_name = socket.gethostname()
      ip = socket.gethostbyname(client_name)
      # create random n
      rest = random.randrange(1, 100, 1)
      # for local purpose and testing multiply clients
      client_ip = "@-".format(ip, str(rest))
      user = user + client_ip
      return user
      except:
      pass


      def main():

      loop = asyncio.get_event_loop()
      coroutine = loop.create_connection(Client, sServer.HOST, sServer.PORT)
      loop.run_until_complete(coroutine)
      loop.run_forever()
      loop.close()


      if __name__ == "__main__":
      main()


      SERVER.py



      import asyncio
      import json
      import sys
      import os.path

      HOST = '127.0.0.1'
      PORT = 6666
      active_users = []
      history =


      class Server(asyncio.Protocol):
      """ Overriding Protocol methods:
      connection_made
      data_received
      connection_lost
      """
      def connection_made(self, transport):
      self.transport = transport
      self.address = transport.get_extra_info('peername')
      print('Connection from '.format(self.address))

      def data_received(self, data):
      stream = data.decode()

      if stream.startswith("USR:"):
      self.username = stream[4:]
      add_user(self)

      elif stream.startswith("MSG:"):
      msg = stream[4:]
      receive_message((self.username + ': ' + msg), self)
      #update_history((self.username + ': ' + msg), self)

      history.update(self.username: msg)
      with open('history.txt', 'a+') as sample:
      for save in [history]:
      sample.write('n'.format(save))

      elif stream == 'EXIT':
      remove_user(self)
      self.transport.close()

      def add_user(user):
      active_users.append(user)
      receive_message(user.username + ' has joined!', user)


      def remove_user(user):
      active_users.remove(user)
      receive_message(user.username + ' has left.', user)

      def receive_message(msg, author):
      print(msg)
      for user in active_users:
      # don't show user's own messages in session
      if user is not author:
      user.transport.write(msg.encode())


      def main():
      loop = asyncio.get_event_loop()
      coroutine = loop.create_server(Server, HOST, PORT)
      server = loop.run_until_complete(coroutine)
      print('Server established on '.format(server.sockets[0].getsockname()))

      try:
      loop.run_forever()
      except KeyboardInterrupt:
      if os.path.exists('history.txt'):
      try:
      os.remove('history.txt')
      sys.exit()
      except OSError:
      pass
      finally:
      server.close()
      loop.close()


      if __name__ == '__main__':
      main()






      python-3.x python-asyncio






      share|improve this question













      share|improve this question











      share|improve this question




      share|improve this question










      asked Mar 26 at 20:26









      BucketheadBuckethead

      4511 bronze badges




      4511 bronze badges

























          0






          active

          oldest

          votes










          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%2f55365685%2fsimple-chat-asyncio-protocol-saving-data-from-transport-stream-into-file%23new-answer', 'question_page');

          );

          Post as a guest















          Required, but never shown

























          0






          active

          oldest

          votes








          0






          active

          oldest

          votes









          active

          oldest

          votes






          active

          oldest

          votes




          Is this question similar to what you get asked at work? Learn more about asking and sharing private information with your coworkers using Stack Overflow for Teams.







          Is this question similar to what you get asked at work? Learn more about asking and sharing private information with your coworkers using Stack Overflow for Teams.



















          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%2f55365685%2fsimple-chat-asyncio-protocol-saving-data-from-transport-stream-into-file%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







          Popular posts from this blog

          How to preserve electronics (computers, tablets and phones) for hundreds of years Announcing the arrival of Valued Associate #679: Cesar Manara Planned maintenance scheduled April 23, 2019 at 23:30 UTC (7:30pm US/Eastern) The network's official Twitter account is up and running again. What content…How might modern humans leave a message for 50,000 years?How would an aquatic race develop computers?How do we make computers care for human life?Keeping supplies for 1000 yearsWhat will cell phones become in 100 years?What body armor protects against a laser?Could a society attain 1800s technology if limited to using copper and bronze?Electricity power (magic) and electronicsScavenging metal resources in post-apocalypse after 100 yearsWhy would precursors create devices that can survive and still work after hundreds of years?

          155 수학 과학 기타 둘러보기 메뉴eh추가해eh문서를 완성해

          Convert JSON to MapSimplest way to convert a string representing JSON array into Java array List of key value pairsHow to take String JSON values into HashMapConvert a JSON String to a HashMapCreating BSON object from JSON stringJSONObject - How to get a value ?Better Map ConstructorReading JSON from Url javaUpdate columns if input values are not null otherwise ignore and keep the existing values of column in databaseHow to store object represented as Json string into Couchbase Lite?Go JSON into MapHow do I efficiently iterate over each entry in a Java Map?Sort a Map<Key, Value> by valuesHow to round a number to n decimal places in JavaCan comments be used in JSON?How do I read / convert an InputStream into a String in Java?How can I pretty-print JSON in a shell script?What is the correct JSON content type?How can I deserialize JSON to a simple Dictionary<string,string> in ASP.NET?Why does Google prepend while(1); to their JSON responses?Parse JSON in JavaScript?