Network Security Internet Technology Development Database Servers Mobile Phone Android Software Apple Software Computer Software News IT Information

In addition to Weibo, there is also WeChat

Please pay attention

WeChat public account

Shulou

How to use Python to create a multi-person chat room

2025-03-04 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >

Share

Shulou(Shulou.com)06/02 Report--

This article mainly introduces how to use Python to create a multi-person chat room, the article is very detailed, has a certain reference value, interested friends must read it!

I. the name of the experiment

Set up chat tools

II. Purpose of the experiment

Master the technology of streaming sockets in Socket programming to realize the chat between multiple computers.

III. Experimental contents and requirements

vii. Master the technology of programming with Socket

viii. Must master multithreading technology to ensure that both parties can send at the same time

ix. Set up chat tools

x. You can chat with multiple people at the same time.

xi. Must use a graphical interface to display the quotations of both sides

4. Experimental environment

Multiple PC, operating system Win7,win10 (32-bit, 64-bit)

Have software python3.6.

5. Operating methods and experimental steps

Server side

1. Call in multithreaded and scoket packages to implement multithreaded connections

two。 Record local address and port, turn on listening, and wait for request

3. Receive a request from a client, establish a connection, assign a thread to each client, and record the client address and port

4. Receives data from a client and forwards it to all clients connected to the server.

5. When a client disconnects, notify all clients connected to the server.

6. The server keeps listening, waiting for other clients to access the server

7. Code

Import socketimport threadingnum=0def chat (service_client_socket Addr): # waiting to receive client messages are stored in two variables service_client_socket and addr: if not addr in user: print ('Accept new connection from% slug% s.'% addr) # if addr is not in the user dictionary, execute the following code for scs in serv_clie_socket: serv_clie_socket [scs] .send (data +') Enter the chat room. '.encode (' utf-8')) # send the data and address of the user dictionary to the client user [addr] = data.decode ('utf-8') # data is the latest customer to enter the chat room After decompression, put into user serv_clie_ socket [service_client_socket] = service_client_socket # put the socket of server and server port number addr in the dictionary # the received message is decoded into utf-8 and stored in the dictionary user, the key name is defined as addr # socket ("you can start chat >") # if addr is in the user dictionary Skip this cycle while True: d = service_client_socket.recv (1024) if (('EXIT'.lower () in d.decode (' utf-8')) | (d.decode ('utf-8') = =' error1')): # if the EXIT is in the sent data name = user [addr] # user dictionary addr key corresponding to the assignment Delete the addr for scs in serv_clie_socket in the user to the variable name user.pop (addr) serv_clie_socket.pop (addr) #: # take out address serv_clie_ sockets [SCS] .send ((name + 'left the chat room.'). Encode ('utf-8' )) # send name and address to the client print ('Connection from% s closed.'% addr) global num num = num-1 break else: print (' "% s" from% SVA% s'% (d.decode ('utf-8')) Addr [0], addr [1]) for scs in serv_clie_socket: # traversing address if serv_clie_ sockets from user [SCS]! = service_client_socket: # address is not equal to addr Execute the following code serv_clie_ socket [SCS]. Send (d) # send data to the client s = socket.socket (socket.AF_INET, socket.SOCK_STREAM) # create the socket object addr = ('127.0.0.1, 9999) s.bind (addr) # bind address and port s.listen (128) print (' TCP Server on', addr [0], ":" Addr [1], ".") user = {} # Storage Dictionary {addr:name} serv_clie_socket = {} # Storage {socket: sockets of different threads} while True: try: print ("waiting to receive a connection request from the client.") Service_client_socket, addr = s.accept () # waiting to receive a connection request from the client print ("received a connection request from the client.") Except ConnectionResetError: print ('Someone left unexcept.') Data = service_client_socket.recv (1024) if data.decode () = 'error1': print (addr, "the login window is closed.") Continue print ("data =", data.decode ()) # assign threads to the server num=num+1 r = threading.Thread (target=chat, args= (service_client_socket,addr), daemon=True) r.start () print ("number of chat rooms:", num)

Client

1. Call in multithreaded, and scoket packages for multithreaded connections, and call into tkinter packages for graphical page display

two。 Record local address and port, send connection request to server, and establish persistent connection

3. Graphical login interface, record the user name entered, and send it to the server

4. When you enter the chat interface, the messages received from the server are displayed on the left and the messages sent to the server are displayed on the right.

5. When you exit, a warning screen pops up. After exiting, disconnect from the server and end.

6. Code

7. Other: the server in the client code is changed to the server address, and the client can run the connection server on different computers and communicate with other clients through the server.

# client import tkinterfrom tkinter import fontimport tkinter.messageboximport socketimport threadingimport timestring=''def my_string (s_input): string= s_input.get () def Send (sock):''the parameter of the method for sending data: sock: define an instantiated socket object server: the server IP and port passed''if stringering messages: Message = name +':'+ string data = message.encode ('utf-8') sock.send (data) if string.lower () =' EXIT'.lower (): exit () def recv (sock): sock.send (name.encode ('utf-8')) while True: data = sock.recv (1024) # plus a timestamp Time_tuple = time.localtime (time.time ()) str = ("{} points {} points" .format (time_tuple [3]) Time_ tuple.decode ('utf-8'), width=40,anchor='w',bg='pink') # the message received is on the left side of rrecv.pack () def left (): global string string = rv1.get () Send (s) if stringwriting stories: rleft = tkinter.Label (ttextwriting stringjewelry widthpieces 40) Anchor='e') # send a message to the right of rleft.pack () rv1.set ('') def Creat (): global name name = n.get () # receiving process tr = threading.Thread (target=recv, args= (s,), daemon=True) # daemon=True indicates the created child thread daemon main thread The main thread exits the child thread and directly destroys the tr.start () l.destroy () e.destroy () b.destroy () t.title ("chat room") t.geometry ("500x600") rL0 = tkinter.Label (the chat room'% name,width=40% s chat room) rL0.pack () rL1 = tkinter.Label (tgrammar textbook 'Please enter the message:', width=20, height=1) rL1.place (xchang0) ) rE1 = tkinter.Entry (t, textvariable = rv1) rE1.place rB1 = tkinter.Button (t, text= "send", command=left) rB1.place (Xero380 def JieShu 450) # sending process def JieShu (): tkinter.messagebox.showwarning (title=' are you sure you want to quit?' , message=' you just clicked the close button') s.send ("error1" .encode ('utf-8')) exit (0) s = socket.socket (socket.AF_INET, socket.SOCK_STREAM) server = (' 10.100.207.40, 9999) s.connect (server) # establish a connection t=tkinter.Tk () t.title ("multi-person chat room") t.geometry ("300x200+500+200") l = tkinter.Label (t Welcome to text=' multiplayer chat room. Please enter your name', width=40, height=8) l.pack () n = tkinter.StringVar () e = tkinter.Entry (t, width=15,textvariable = n) e.pack () rv1 = tkinter.StringVar () name = n.get () b = tkinter.Button (t, text= "login", width=40, height=10,command=Creat) b.pack () t.protocol ("WM_DELETE_WINDOW", JieShu) t.mainloop () s.close () VI, experimental data record and result analysis

1. Server starts, waiting for client connection request

two。 The client requests the service, the client pops up the login window, and enter the user name to log in.

3. The server receives requests, allocates ports, and continues to listen for requests from other clients

4. After the client logs in, enter the chat window

5. Users who enter the chat room can send messages that can be received by other users and seen by the server.

6. The client exits the connection, other users can receive it, and the server can see

7. Other clients can enter the chat room midway.

The above is all the contents of the article "how to use Python to create a multi-person chat room". Thank you for reading! Hope to share the content to help you, more related knowledge, welcome to follow the industry information channel!

Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.

Views: 0

*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.

Share To

Development

Wechat

© 2024 shulou.com SLNews company. All rights reserved.

12
Report