Use the Python Tornado framework to implement a one-to-one chat program _python

Source: Internet
Author: User

To talk by train of thought:

Similar to the micro-letter, click on the user can enter a one-to-one chat page, and the Chat box list contains all the chat record of a one-to-one chat box, click into the chat page.
"Data Structure"

Since both sides have chat records, each chat actually has to store two copies, the design of the data structure is as follows:

A:

User_a = {"id": 1, "name": "A"}

B:

User_b = {"id": 2, "name": "B"}

A's chat record:

Chat_a = {"id": 1, "User": 1, "who": 2, "name": "B", "new": 0, msg:[]}

B's chat record:

Chat_b = {"id": 2, "User": 2, "who": 1, "name": "A", "new": 0, msg:[]}

MSG is actually a list, structured as follows: Msg = {"User": Sender ID, "name": Sender name, "date": Send Time, "content": Message content}
"Business logic"

When a clicks the name of B in the buddy list –> into the chat box (according to the two sides ID through the field user, who find the corresponding Chat_a,chat = Coll.find_one ({"User": user_a[' id '), "who": user_b[' id ' If the chat does not exist, create chat_a with both sides ID)

Send messages (update chat_a and chat_b, create chat_b If Chat_b does not exist, update chat_b ' new ' if chat_b[is not in line) = 1)

A Delete chat box (delete chat_a)
"Log client connections"

Because it is multiple one-to-one chats, you cannot use the set in the tutorial to record the connection directly.

The final decision is to use a dict, with a string of two user ID stitching as key, with the list stored client connection.

... Sockethandler (...):

Chats = Dict () ...
def on_open (self):
  ...
  #通过双方id来生成一个独一无二的字符串
  min = user_a[' id ']
  max = user_b[' id '
  if min >max:
    max = user_a[' id '
    min = user_b[' id '
  key = str (user_a[' ID ']) + "_" +str (user_b[' id ')
  #判断当前会话是否存在, existing to add the current user
  if key in chats:
    sockethandler.chats[key].append (self)
  #不存在则创建会话 and adds the current user to the
  else
    sockethandler.chats[key] = [Self]

"Send Message"

Call the Send function from the client to update the two chat records after accepting the arguments in the service-side on_message function. Then call Send_to_all (key, message) to update the chat window.
Send notification/update Chat window

When you update the chat log in the database and update the HTML in the Chat window, you need to notify the person who connected the session.

According to the way we record the connectors, the corresponding notification function is as follows:

def send_to_all (key,message): For
  user in Sockethandler.chats[key]:
    user.write_message (json.dumps (message) )

"Close Connection"

According to the way we record the connectors, the corresponding shutdown function is as follows:

def on_close (self):
  ...
  #用on_open函数中的方法构造key
  if key in Sockethandler.chats:
    sockethandler.chats[key].remove (self) #删除当前连接
    if Len (Sockethandler.chats[key]) = = 0:
      del Sockethandler.chats[key] #当会话无连接者则删除会话

Through the above transformation, to achieve multiple one-on-one chat function

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.