Python implements network multi-person chat room, web development is actually so simple

Network Multi-Person Chat Room

File structure:

  chatroom
- client.py_client code
- language.py_Language File
- server.py_server-side code
settings.py Settings File

  0 directories, 4 files

Use module:

  • os
  • sys
  • socket
  • select

Train of thought:

  • settings.py, defining HOST, PORT, ADDR, buffersize, language, curuser and other variables.
  • server.py, the server code, uses the select module selection method to realize IO multiplexing to monitor sys.stdin input and client connection, to achieve communication with the client, and to send the information received from the client to each client.
  • client.py, client code, also uses IO multiplexing to listen to the client receiving information and sys.stdin input information at the same time, realizes communication with the server, and indirectly realizes group chat with other clients.
  • language.py, language files, support for Chinese and English.

Code:

settings.py

# settings.py

HOST = '0.0.0.0'      # host name
PORT = 5555            # Port number
buffersize = 1024    # Buffer size
ADDR = HOST, PORT    # address

languages = ['cn', 'en']      # 'cn'- > Chinese
language = 'cn'                # 'en'- > English

curuser = ''  # Current user

language.py

# language.py

from settings import language

if language == 'en':
    administrator = 'Administrator'
    txt_administrator_close_chatroom = 'Chatroom closed by Administrator.'
    txt_uesr_enter_chatroom = 'entered the chatroom.'
    txt_user_quit_chatroom = 'quited the chatroom.'
    txt_username = 'username> '
    txt_user_already_exists = 'Username already exists!'
    txt_connect_to = 'Connected to'
    txt_connect_from = 'Connected from'
elif language == 'cn':
    administrator = 'Administrators'
    txt_administrator_close_chatroom = 'The administrator closed the chat room.'
    txt_uesr_enter_chatroom = 'Enter the chat room.'
    txt_user_quit_chatroom = 'Exit the chat room.'
    txt_username = 'User name> '
    txt_user_already_exists = 'The username already exists.'
    txt_connect_to = 'connection to'
    txt_connect_from = 'Connection from'

server.py

# server.py

# Import System Module
import os, sys
# Import Network Programming (Transport Layer) Module
from socket import *
# IO multiplexing module
from select import select
# Setup module
from settings import *
# Language module
from language import *

def main():
    'main Main function'
    server = socket(AF_INET, SOCK_STREAM)  # Establishing TCP sockets
    server.setsockopt(SOL_SOCKET, SO_REUSEADDR, 1)  # Setting ports for immediate reuse
    server.bind(ADDR)  # Binding address
    server.listen()  # Monitor

    # Receiver function
    accept(server)

def accept(server):
    'accept Server acceptance function'

    # Implementation of IO Multiplexed Monitoring Transmission by select Module
    rlist = [server, sys.stdin]
    wlist = []
    xlist = []

    while True:
        rs, ws, xs = select(rlist, wlist, xlist)

        for r in rs:
            if r is server:
                # Server accepts client connection
                conn, addr = server.accept()
                # Call the validate function to check the username
                if validate(conn):
                    # Add client sockets to rlist to listen
                    rlist.append(conn)
                    # If the username registration is successful
                    print(txt_connect_from, addr)
                else:
                    conn.close()
            elif r is sys.stdin:
                # The server sends system (administrator) messages to all clients
                data = sys.stdin.readline()
                if data == '\n':
                    # If the server enters a carriage return, it exits
                    for c in rlist[2:]:
                        c.send(b'\n')
                        c.close()
                    server.close()
                    print(txt_administrator_close_chatroom)
                    os._exit(0)
                else:
                    # Notify all clients if the server enters a normal statement
                    data = administrator + ': ' + data
                    for c in rlist[2:]:
                        c.send(data.encode())
            else:
                # The server receives messages from the client and forwards them to all clients
                data = r.recv(buffersize)
                if not data:
                    # Close the client
                    r.close()
                    rlist.remove(r)
                else:
                    # Forwarding information to other clients
                    print(data.decode(), end='')
                    for c in rlist[2:]:
                        if c is not r:
                            c.send(data)

def validate(client):
    'Verify username validate username'
    name = client.recv(buffersize).decode()
    # print(name.decode())
    # print(users)
    if name in users:
        client.send(b'Username already exists!')
        return False
    else:
        users.append(name)
        client.send(b'Welcome!')
        return True

if __name__ == '__main__':
    # Global variables to manage user information
    users = []

    # Main function
    main()

client.py

# client.py

# Import System Module
import os, sys
# Import Network Programming (Transport Layer) Module
from socket import *
# IO multiplexing module
from select import select
# Setup module
from settings import *
# Language module
from language import *

def main():
    'main Main function'
    client = socket(AF_INET, SOCK_STREAM)  # Establishing TCP sockets

    # Login function
    if login(client):
        # Connection function
        connect(client)

def connect(client):
    'connect Client Connection Function'

    # Implementation of IO Multiplexed Monitoring Transmission by select Module
    rlist = [client, sys.stdin]
    wlist = []
    xlist = []

    while True:
        rs, ws, xs = select(rlist, wlist, xlist)

        for r in rs:
            if r is client:
                # Accept messages from servers
                data = client.recv(buffersize)
                if data.decode() == '\n':
                    # If the message is return, the chat room is closed.
                    client.close()
                    print(txt_administrator_close_chatroom)
                    os._exit(0)
                else:
                    # Print received information
                    print(data.decode(), end='')
            elif r is sys.stdin:
                # Send a message to the server
                data = sys.stdin.readline()
                if data == '\n':
                    # If you return, send an exit message, close the client and exit the chat room
                    data = curuser + ': ' + txt_user_quit_chatroom + '\n'
                    client.send(data.encode())
                    client.close()
                    os._exit(0)
                else:
                    # Send information to server
                    data = curuser + ': ' + data
                    client.send(data.encode())

def login(client):
    'Login function login'
    # Managing users with global variables
    # Let the client enter the name first
    global curuser
    curuser = input(txt_username)
    # Connect to the server and send the username to verify
    client.connect(ADDR)  # Connect to the server address
    print(txt_connect_to, ADDR)
    client.send(curuser.encode())
    data = client.recv(buffersize)
    if data.decode() == 'Username already exists!':
        # If the username already exists, requiring re-entry
        print(txt_user_already_exists)
        return False
    else:
        # Send information to server, inform server user to enter chat room
        # -*- Because the listener is sys.stdin.readline(), a newline must be added at the end to clear the blockage.-*-
        data = curuser + ': ' + txt_uesr_enter_chatroom + '\n'
        client.send(data.encode())
        return True

if __name__ == '__main__':
    main()

Operating screenshots:

If you are still confused in the world of programming, you can join our Python Learning button qun: 784758214 to see how our predecessors learned. Exchange of experience. From basic Python script to web development, crawler, django, data mining, zero-base to actual project data are sorted out. To every Python buddy! Share some learning methods and small details that need attention. Click to join us. python learner gathering place

Conclusion:

  • Before typing the code, we must first plan and outline the general route of the project.
  • The implementation of the project should start from the basic foundation. The realization of such a multi-person chat room between networks must start from the establishment of the server and client, not from the surface. For example, if we want to make a graphical user interface application of multi-person chat room on the network, we can never write the implementation of graphical user interface first, even if the final graphical user interface is so beautiful, if we can not achieve network communication, it will be useless.
  • For errors in the project, more comments should be added to facilitate future reading, find useful knowledge on the Internet, you can copy the website, write in the project document, convenient for future occasional needs.

Tags: Web Development network socket Python Programming

Posted on Tue, 10 Sep 2019 19:13:20 -0700 by lonewolf217