20214321 Wu Mengyuan, "Python Programming" Experiment 4 Report

20214321 2022-2022-4 "Python Programming" Experiment 4 Report

Course: "Python Programming"
Class: 2143
Name: Wu Mengyuan
Student ID: 20214321
Experimental teacher: Wang Zhiqiang
Experiment Date: May 4, 2022
Compulsory/Elective: Public Elective

1. Experiment content

     A multi-person online chatter is written in python with socket and multi-threaded programming. The client and the server communicate through socket sockets (TCP). The chat messages can be recorded in the client, and the user can open it and review it by himself. .

2. Experimental procedure

(1) Server

The basic configuration of the server is written first

 

In the server, instantiate each socket object connected to the client, and store each socket in a list. Join the loop, in the loop, the server will continue to establish a connection with the connected client and open a thread to communicate with it.

 

In the thread, the received message will be divided by strings to obtain the client nickname and message. The first is to identify the administrator, and the administrator can shut down the server; the other is to allow each user to Identify who sent the message.

 

After the discrimination operation is done, the user nickname and the information are spliced ​​together, and the message is sent to each socket object through the for loop traversing the list.

 

(2) Client

Configuration information is also required in the client

 

There will also be a thread in the client, in which there is a loop that continuously accepts server messages.

 

After the client connects to the server, enter the nickname in the middle to start chatting.

 

At the same time, the client has a file operation to write and save the chat message for the user to review.

 

Source code:

 1 from socket import *
 2 from threading import Thread
 3 
 4 # configuration information
 5 IP = '127.0.0.1'  # address
 6 PORT = 50000  # The port number
 7 BUF_LEN = 512  # once from socket Byte data size of buffer input
 8 MASTER_NAME = '1001'
 9 MASTER_COMMAND = '202143xxEXIT'
10 DECOLLATOR = '|'
11 OPENSIGN = True
12 
13 # socket
14 listenSocket = socket(AF_INET, SOCK_STREAM)  # instance one socket object
15 listenSocket.bind((IP, PORT))  # socket Bind address and port
16 listenSocket.listen(20)  # Up to 20 users
17 print(f'The server started successfully at{PORT}Port waiting for client connection...')
18 
19 
20 # This is the function executed by the new thread, each thread is responsible for communicating with a client
21 def client_handler(data_Socket, add_r):
22     while True:
23         recv_ed = data_Socket.recv(BUF_LEN)
24         # Returns an empty string when the other party closes the connection
25         if not recv_ed:
26             for i in USER:
27                 if i == data_Socket:
28                     del i
29             print(f'client{add_r} connection closed')
30             break
31 
32         # The byte data read is bytes Type, need to be decoded as a string, split the string to get information
33         u_nick = recv_ed.decode().split(DECOLLATOR)[0]
34         # Nickname processing not obtained
35         if u_nick == '':
36             u_nick = 'Handsome guy or girl who is too lazy to enter a nickname'
37 
38         # message splicing
39         msg = recv_ed.decode().split(DECOLLATOR)[1]
40         info = u_nick+':'+msg
41         print(f'receive{add_r}information: {info}')
42 
43         # Admin shuts down server processing
44         if info == MASTER_NAME+':'+MASTER_COMMAND:
45             for i in USER:
46                 i.send('Server is down'.encode())
47             listenSocket.close()
48             break
49 
50         # Traverse all clients and send messages to each client
51         for i in USER:
52             i.send(f'{info}'.encode())
53     data_Socket.close()
54     for i in USER:
55         i.close()
56 
57 
58 # Build a list and collect clients socket
59 USER = []
60 
61 while True:
62     # In a loop, new connection requests are always accepted
63     dataSocket, addr = listenSocket.accept()  # Establish communication with the client
64     USER.append(dataSocket)
65     addr = str(addr)
66     print(f'a client{addr}link successfully')
67 
68     # Create a thread to handle messaging with this client
69     th = Thread(target=client_handler, args=(dataSocket, addr))
70     th.start()
 1 from socket import *
 2 from threading import Thread
 3 from time import localtime, strftime, time
 4 
 5 # configuration information
 6 IP = '127.0.0.1'
 7 SERVER_PORT = 50000
 8 BUF_LEN = 512
 9 DECOLLATOR = '|'
10 
11 # socket
12 dataSocket = socket(AF_INET, SOCK_STREAM)
13 dataSocket.connect((IP, SERVER_PORT))
14 
15 
16 # This is the function executed by the new thread to receive server messages
17 def receive_handler(data_Socket, ):
18     while True:
19         receive = data_Socket.recv(BUF_LEN)
20         print(receive.decode())
21         if not receive:
22             break
23         # Write another user's chat
24         get_time = strftime('%H:%M:%S', localtime(time()))
25         file1.write(str(get_time))
26         file1.write('\n')
27         file1.write(receive.decode())
28         file1.write('\n')
29     data_Socket.close()
30     dataSocket.close()
31     exit()
32 
33 
34 # Open the folder, count the chatter usage time
35 file1 = open("test", "a+", encoding="GBK")
36 Open_time = strftime('%H:%M:%S', localtime(time()))
37 file1.write('Start Time:'+str(Open_time))  # Write the open time and record the chat in what time period
38 file1.write('\n')
39 
40 # Create a thread and receive server messages
41 th = Thread(target=receive_handler, args=(dataSocket, ))
42 th.start()
43 
44 # Enter nickname
45 nickname = input('Please enter your nickname:')
46 print('ready to chat')
47 
48 # Looping: keep sending messages to the server
49 while True:
50 
51     toSend = input()
52     now_time = strftime('%H:%M:%S', localtime(time()))
53     file1.write(str(now_time))
54     file1.write('\n')
55     file1.write(toSend)
56     file1.write('\n')
57     if toSend == '':
58         now_time = strftime('%H:%M:%S', localtime(time()))
59         file1.write('You have closed the chat room, closing time:'+str(now_time))
60         file1.write('\n')
61         break
62     dataSocket.send((nickname+DECOLLATOR+toSend).encode())
63 
64 dataSocket.close()
65 file1.close()

 

 

3. Summary of the whole class

I have learned a lot in this semester's python class. Mr. Wang is a protégé of the python language and led us into the practice of python.

The master led in the door and practiced in himself. This sentence is one of my feelings in the python class. Mr. Wang speaks very quickly, and I feel a lot about what a class will teach a beginner like me. In addition, we only have a class once a week. If there is no review after class It's easy to forget what was covered in the last class. I feel that although our course is simple, we learn a lot of things and cover a wide range of things. We need to check a lot of things online, and we also need to learn a lot of content online.

Another feeling of this lesson is that practice is the only criterion for testing truth. The content I have been exposed to in the python class has never been touched before. When I conduct some experiments, I am always timid and afraid to do it as if I am afraid of breaking something. After conducting several experiments, I understand that doing experiments means "fixing". Don't be afraid to break the code. Ask and check if you have any questions. Nothing can't be solved.

To sum up, this lesson is full of harvest, but also let go of the courage and dare to do something.

 

4. References

1. Python3 multithreading | rookie tutorial

2. [python project combat] Create your own multiplayer chat room

Posted by cheerio on Tue, 31 May 2022 16:38:49 +0530