Socket simulation service area and client

Use code to achieve:

# Server 

from socket import * 
from threading import Thread 

# Receive client information and connection status 
def recv_data(client_socket,client_info): 
    while True: 
        recv_data = client_socket.recv(1024) 
        recv_content = recv_data.decode('gbk') 
        print(f 'The client said: {recv_content}, from: {client_info}') 
        if recv_content == 'end': 
            print('End message') 
            break 

# The server sends information to the client 
def send_data(): 
    while True: 
        msg = input ('>') 
        client_socket.send(msg.encode('gbk')) 
        if msg == 'end':
            print('End of message') 
            break 


if __name__ == '__main__':
    # Create socket 
    server_socket = socket(AF_INET,SOCK_STREAM) 
    # Change to the IP of the machine, 8888 is the interface used 
    server_socket.bind(('192.168.10.124',8888)) 
    # Start passive connection, how many clients to set Can connect 
    server_socket.listen(5) 
    print('Waiting for connection!') 
    while True: 
        client_socket, client_info = server_socket.accept() 
        print("A client successfully established a connection!") 
        t = Thread(target=recv_data, args= (client_socket, client_info)) 
        #Create a thread to process the information received from the client 
        t1 = Thread(target=send_data) 
        #Create a thread to send and receive information from the server 
        t.start() 
        #Start the thread 
        t1.start()

# Client 
from socket import * 
from threading import Thread 

def recv_data(): 
    while True: 
        # Receive server-side data 
        recv_data = client_socket.recv(1024) 
        recv_content = recv_data.decode('gbk') 
        print(f'The server said: {recv_content}') 
        if recv_content == 'end': 
            print('End message') 
            break 


#You can send information to the server 
def send_data(): 
    while True: 
        msg =input('>') 
        client_socket.send(msg.encode ('gbk')) 
        if msg == 'end': 
            print('message end') 
            break 



if __name__ == '__main__':
    # create socket
    client_socket = socket(AF_INET,SOCK_STREAM)
    # Change to the IP of the machine, 8888 is the interface used 
    client_socket.connect(('192.168.10.124',8888)) 
    t1 = Thread(target=recv_data) 
    t2 = Thread(target=send_data) 
    t1.start() 
    t2. start() 
    t1.join() 
    t2.join() 
    client_socket.close()

Guess you like

Origin blog.csdn.net/NOguang/article/details/131688507