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

          Kamusi Yaliyomo Aina za kamusi | Muundo wa kamusi | Faida za kamusi | Dhima ya picha katika kamusi | Marejeo | Tazama pia | Viungo vya nje | UrambazajiKuhusu kamusiGo-SwahiliWiki-KamusiKamusi ya Kiswahili na Kiingerezakuihariri na kuongeza habari

          SQL error code 1064 with creating Laravel foreign keysForeign key constraints: When to use ON UPDATE and ON DELETEDropping column with foreign key Laravel error: General error: 1025 Error on renameLaravel SQL Can't create tableLaravel Migration foreign key errorLaravel php artisan migrate:refresh giving a syntax errorSQLSTATE[42S01]: Base table or view already exists or Base table or view already exists: 1050 Tableerror in migrating laravel file to xampp serverSyntax error or access violation: 1064:syntax to use near 'unsigned not null, modelName varchar(191) not null, title varchar(191) not nLaravel cannot create new table field in mysqlLaravel 5.7:Last migration creates table but is not registered in the migration table

          은진 송씨 목차 역사 본관 분파 인물 조선 왕실과의 인척 관계 집성촌 항렬자 인구 같이 보기 각주 둘러보기 메뉴은진 송씨세종실록 149권, 지리지 충청도 공주목 은진현