Study Notes (31): 21 days clearance Python (Video Lesson only) - Use socket communication and add multithreading

Learning immediately: https://edu.csdn.net/course/play/24797/282211?utm_source=blogtoedu

Server:

import socket, threading
import datetime, os

client_list = []
st = socket.socket(socket.AF_INET, socket.SOCK_STREAM, 0)
st.bind(('192.168.0.118', 8888))
st.listen()


def server_target(server_socket, addr):
    while True:
        cval = server_socket.recv(2048).decode('UTF-8')
        if cval is not None:
            print('客户端:', addr[0], ',内容:', cval)
            for cl in client_list:
                cl.send(('主机回复:%s' % cval).encode('utf-8'))
            with open('txtinfo.txt', 'ab', True) as f:
                f.writelines((str(datetime.datetime.today()).encode('UTF-8'),
                              ( '- Client Address:' + addr [0] + '- sending content:' + CVAL) .encode ( 'UTF-. 8'),
                              (( '- Host Reply:% S' CVAL%) + os.linesep) .encode ( 'UTF-. 8'))) 
the while True: 
    Socket client address and # represents the communication 
    vala, addr = st.accept () 
    # sockt stored corresponding to the list 
    client_list.append (Vala) 
    Print (addr) 
    with Open ( 'txtinfo.txt', 'ab &', True) AS F: 
        f.write ((STR (datetime.datetime.today () ) + '- client address:' + STR (addr [0]) + os.linesep) .encode ( 'UTF-. 8')) 
        # corresponding to the client to start the threads sockt 
    threading.Thread (target = server_target , args = (vala, addr) ). start ()

 

 

Client:
 

'' ' 
Created by threading.Thread thread 

' '' 
Import socket, Threading 

# simple client 
# ST = socket.socket (socket.AF_INET, socket.SOCK_STREAM, 0) 
# # call the connect server 
# st.connect (( '192.168.0.118', 8888)) 
# # after successful connection, once established, server to client connection is successful virtual link 
# Print (st.recv (2048) .decode ( 'UTF-. 8')) 

ST = socket.socket ( socket.AF_INET, socket.SOCK_STREAM, 0) 
st.connect (( '192.168.0.118', 8888)) 


# reading 
DEF get_server (client_socket): 
    the while True: 
        getser = client_socket.recv (2048) .decode ( 'UTF- 8 ') 
        # If the returned data is not empty 
        IF getser None not iS: 
            Print (getser) 
        the else:
            break


of the threading.Thread (target = get_server, args = (ST,)) Start (). 
# Send 
the while True: 
    InP = INPUT () 
    # input is empty or if the exit loop is exited 
    if inp is None or inp == ' exit' : 
        BREAK 
    # transmit data 
    st.send (inp.encode ( 'UTF-8 '))
Published 39 original articles · won praise 29 · views 896

Guess you like

Origin blog.csdn.net/happyk213/article/details/105267690