python Implementation of Simple Chat Room of Linux Terminal

  • 2021-11-13 08:31:17
  • OfStack

This article example for everyone to share python to achieve simple chat room specific code, for your reference, the specific content is as follows

Group chat room

1. Function: Similar to qq group chat function

1. Someone needs to enter a name when entering the chat room, and the name cannot be duplicated

2. When someone enters the chat room, others will be notified
xxx Enter the chat room

3.1 When a person sends a message, others will receive a message
xxx: xxxxxxxx

4. If someone quits the chat room, others will be notified
xxx Exit Chat Room

5. Extended function: Message announcement on the server side, and everyone can receive the message sent by the server side
Administrator message: xxxxxxxx

2. Determine the technology model

1. Server and client

The server handles the request and sends the administrator message
The client performs various functions

2. Socket selection: udp socket

3. Messaging model: Forwarding
Client ~ > Server side ~ > Other clients

4. Store user information: {name: addr}

5. Handle the transceiver relationship: Multi-process handles the transceiver separately

3. Considerations

1. Design the package

2. Write a functional module and test a module

3. Pay attention to the addition of comments


#coding =utf-8
'''
chat room
env:python3.5
exc:socket and fork
name:mianmabb
email:mianmabb@163.com
服务端功能:
1.搭建网络通信
2.处理进入聊天室
    * 接收姓名
    * 判断是否允许进入
    * 将结果反馈给客户端
    * 如果不允许则结束,允许则将用户插入数据结构
    * 给其他人发送通知
3.处理聊天
    * 接收消息,判断消息类型,分为L(输入姓名),C(发消息),Q(退出聊天室)
    * 将消息转发
4.处理退出聊天室
5.发送管理员消息 
'''

from socket import *
from os import *
from sys import *

user = {}   #创建空字典用来存储用户的昵称和地址

#处理登录
def do_login(s,name,addr):
    if name in user:    #判断昵称是否已经存在
        s.sendto('该昵称已被占用'.encode(),addr)
        return
    else:    #昵称不存在,则发送约定好的'OK'
        s.sendto(b'OK',addr)

    #功能:有人进入聊天室,其他人会收到消息
    msg = '\n   欢迎 %s 进入聊天室   '%name
    for i in user:    #发送该条消息给其他用户
        s.sendto(msg.encode(),user[i])
    
    user[name] = addr   #将该用户插入数据结构(字典)

#处理聊天
def do_chat(s,name,text):
    msg = '%s : %s'%(name,text)   #设置消息显示格式
    for i in user:
        s.sendto(msg.encode(),user[i])

#处理退出
def do_quit(s,name):
    msg = '%s 退出了聊天室'%name
    for i in user:
        if i != name:   #给其他人发送该用户退出的消息
            s.sendto(msg.encode(),user[i])
        else:   #给该用户客户端发送约定好的EXIT让父进程退出
            s.sendto(b'EXIT',user[i])
    del user[name]   #删除字典中该用户


#处理请求
def do_request(s):
    #循环接受所有客户请求
    while True:
        try:
            data,addr = s.recvfrom(1024)
        except KeyboardInterrupt:    #捕获父进程直接退出错误
            exit('服务端退出!')

        # print(data.decode())
        msgList = data.decode().split()   #按空格拆分为列表,方便索引

        if msgList[0] == 'L':    #判断消息类型
            do_login(s,msgList[1],addr)

        elif msgList[0] == 'C':
            text = ' '.join(msgList[2:])  #将消息中可能有的空格加回来
            do_chat(s,msgList[1],text)
        elif msgList[0] == 'Q':
            do_quit(s,msgList[1])



def main():
    s = socket(AF_INET,SOCK_DGRAM)
    ADDR = ('0.0.0.0',8888)
    s.bind(ADDR)

    #创建进程
    pid = fork()
    if pid < 0:
        print('Error')
    elif pid == 0:   #子进程用来发送管理员消息
        while True:
            try:
                text = input('管理员 : ')
            except KeyboardInterrupt:    #捕获子进程直接退出错误
                exit()

            msg ='C 管理员 %s'%text
            s.sendto(msg.encode(),ADDR)

    else:   #父进程用来处理请求
        do_request(s)



main()

Client functionality:


'''
1. Set up communication 
2. Enter the chat room 
    *  Enter a name 
    *  Send to server 
    *  Receive feedback from the server 
    *  Re-enter if not allowed, enter chat room if allowed 
    *  Create a new process for messaging 
3. Chat 
    *  Send a message in a loop    Message types are divided into L( Enter a name ),C( Send a message ),Q( Quit the chat room )
    *  Receive messages cyclically 
4. Quit the chat room 
5. Accept administrator messages 
'''


from socket import *
from os import *
from sys import *

ADDR = ('127.0.0.1',8888)    # Fill in the server address 

# Send a message in a loop 
def send_msg(s,name):
    while True:
        try:
            text = input()   # The customer enters the message to send 
        except KeyboardInterrupt:   # Child process   Prevent users Ctrl+C Direct exit 
            text = 'quit'

        if text.strip() == 'quit':    # Specified input quit Quit 
            msg = 'Q ' + name     # Message type , Name 
            s.sendto(msg.encode(),ADDR)
            exit(' You have quit the chat room ')
        else:
            msg = 'C %s %s'%(name,text)  # Message type , Name , Message 
            s.sendto(msg.encode(),ADDR)

# Receive information cyclically 
def recv_msg(s):
    while True:
        try:
            data,addr = s.recvfrom(1024)
        except KeyboardInterrupt:    # Parent process   Prevent users Ctrl+C Direct exit 
            exit()
        if data.decode() =='EXIT':   # When the user exits , There is no need to receive messages , Agreement EXIT Let the parent process exit 
            exit()   # Exit the parent process 

        print(data.decode())


# Create a network connection 
def main():
    s = socket(AF_INET,SOCK_DGRAM)
    while True:
        name = input(' Please enter a nickname :')     # Enter a name 
        if not name:
            return
        msg = 'L ' +name
        # Send a request 
        s.sendto(msg.encode(),ADDR)
        # Waiting for a reply 
        data,addr = s.recvfrom(1024)
        if data.decode() == 'OK':
            print(' You have entered the chat room ')
            break
        else:   # Login failed 
            print(data.decode())  # Print server error messages directly 
        
    # Create process 
    pid = fork()
    if pid < 0:
        print('Error')
    elif pid == 0:   # Child processes send messages 
        send_msg(s,name)
    else:      # Parent process receives messages 
        recv_msg(s)


main()

Run the server first, then the client


Related articles: