SoFunction
Updated on 2024-11-18

Example of building a multiplayer chat room using Python in detail

I. Name of experiment

Setting up a chat tool

II. Purpose of the experiment

Master the technique of streaming sockets in socket programming for chatting between multiple computers.

III. Experimental content and requirements

Mastery of programming techniques utilizing sockets

viii.Multi-threading techniques must be mastered to ensure that both parties can send simultaneous

ix. Establishment of a chat tool

x. Can chat with multiple people at the same time

xi.A graphical interface must be used to display the quotations of both parties

IV. Experimental environment

Multiple PCs, OS Win7, Win10 (32-bit, 64-bit)

With software python 3.6 .

V. Methods and experimental steps

server-side

1. Called into the multi-threaded, with scoket package for the implementation of multi-threaded connections

2. Record the local address and port, open listening, waiting for the 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. Receive data sent by a client and forward it to all clients connected to the server.

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

6. The server stays in a listening state, waiting for other clients to access the server.

7. Code

import socket
import threading

num=0

def chat(service_client_socket,addr): 
    # Waiting to receive client messages stored in 2 variables service_client_socket and addr.
    if not addr in user:  
        print('Accept new connection from %s:%s...' % addr)
        # If addr is not in the user dictionary then 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] = ('utf-8')  #data is the most recent customer to enter the chat room, unzip it and put it into user
        serv_clie_socket[addr] = service_client_socket # Put the socket with the server and server port number addr into the dictionary
        # Incoming messages are decoded to utf-8 and stored in the dictionary user, with the key defined as addr.
    #print("You can start chatting now>>>>>>")
    # If addr is in the user dictionary, skip this loop.
    while True:
        d = service_client_socket.recv(1024)
        if (('EXIT'.lower() in ('utf-8'))|(('utf-8') == 'error1')):
            #If EXIT is in the data being sent
            name = user[addr]   
            #The value corresponding to the user dictionary's addr key is assigned to the variable name.
            (addr) 
            serv_clie_socket.pop(addr)     
            #Delete the addr in user
            for scs in serv_clie_socket:     
                # Take the address from the user
                serv_clie_socket[scs].send((name + ' Leaving the chat room ... ').encode('utf-8'))     
                # Send name and address to the client
            print('Connection from %s:%s closed.' % addr)
            global num
            num = num-1
            break
        else: 
            print('"%s" from %s:%s' %(('utf-8'), addr[0], addr[1]))  
            for scs in serv_clie_socket:    
                # Iterate from user to address.
                if serv_clie_socket[scs] != service_client_socket:  
                    When #address is not equal to addr, execute the following code
                    serv_clie_socket[scs].send(d)     
                    # Send data to the client

s = (socket.AF_INET, socket.SOCK_STREAM)  # Create socket objects

addr = ('127.0.0.1', 9999)
(addr)  # Bind addresses and ports

(128)

print('TCP Server on', addr[0], ":",addr[1],"......")

user = {}  # Store dictionary {addr:name}
serv_clie_socket = {} #Store {socket: sockets for different threads}
while True:
    try:
        print("Waiting to receive connection requests from clients ....")
        service_client_socket, addr = () # Waiting to receive connection requests from clients
        print("Connection request received from client ....")
    except ConnectionResetError:
        print('Someone left unexcept.')
    data = service_client_socket.recv(1024)
    if ()=='error1':
        print(addr,"Closed the login window...")
        continue
    print("data = ",())
    
         
    #Assign threads to servers
    num=num+1
    r = (target=chat, args=(service_client_socket,addr), daemon=True) 
    ()
    print("Chat room count:",num)


client (computing)

1. Into the multi-threaded, and scoket package for the implementation of multi-threaded connections, into the tkinter package for graphical page display

2. Record the local address and port, send a connection request to the server, establish a continuous connection

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

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

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

6. Code

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

# Client
import tkinter
from tkinter import font
import 
import socket
import threading
import time

string=''
def my_string(s_input):
    string = s_input.get()

def Send(sock):
    '''
        Methods for sending data
        Parameters:
            sock: define an instantiated socket object
            server: IP and port of the server passed
    '''
    if string!='':
        message = name + ' : ' + string
        data = ('utf-8')
        (data)
        if () == 'EXIT'.lower():
            exit()


def recv(sock):
    (('utf-8'))
    while True:
        data = (1024)
        # Add a time stamp
        time_tuple = (())
        str = ("{}point (in space or time){}ingredient".format(time_tuple[3],time_tuple[4]))
        rrecv = (t,text=('utf-8'),width=40,anchor='w',bg='pink')#Received messages to the left
        ()

def left():
    global string
    string = ()
    Send(s)
    if string!='':
        rleft = (t,text=string,width=40,anchor='e')# Sent messages to the right
        ()
        ('')

def Creat():
    global name
    name = ()
    
    # Receiving process
    tr = (target=recv, args=(s,), daemon=True)
    # daemon=True means that the created sub-thread guards the main thread, and the sub-thread is destroyed directly when the main thread exits.
    ()
     
    ()
    () 
    ()
    ("Chat room.")
    ("500x600")
    rL0 = (t,text='%s chat room'%name,width=40)
    ()
    rL1 = (t,text='Please enter a message:',width=20, height=1)
    (x=0,y=450)
    rE1 = (t, textvariable = rv1)
    (x=200,y=450) 
    rB1 = (t, text="Send.",command=left)  
    (x=380,y=450)
    # Sending process

def JieShu():
    (title='Are you sure you want to quit?', message='You just clicked the close button')
    ("error1".encode('utf-8'))
    exit(0)   
    
s = (socket.AF_INET, socket.SOCK_STREAM)    
server = ('10.100.207.40', 9999)
(server)# Establish connection
t=()
("Multiplayer Chat Room")
("300x200+500+200")
l = (t,text='Welcome to the multiplayer chat room, please enter your name',width=40, height=8)
()
n = ()
e = (t, width=15,textvariable = n)
() 
rv1 = ()
name = ()

b = (t, text="Login",width=40, height=10,command=Creat) 

()
("WM_DELETE_WINDOW", JieShu)
()

()

VI. Recording of experimental data and analysis of results

1. Server starts and waits for client connection request

2. The client requests the service, the client pops up the login window, enter the user name to login

3. The server receives the request, allocates a port, and continuously listens for requests from other clients.

4. Enter the chat window after logging in the client

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

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

7. Other clients can enter the chat room in the middle of a session.

Above is the use of Python to create a multiplayer chat room example details, more information about Python multiplayer chat room please pay attention to my other related articles!