[Python] Socket programming (多執行緒)

Server端:

import socket
import time
import SocketServer
import threading

class ThreadedTCPServer(SocketServer.ThreadingMixIn,SocketServer.TCPServer):
    pass

class ThreadedTCPRequestHandler(SocketServer.BaseRequestHandler):
        
    def handle(self):
        BUFSIZE = 1024
        print('Connect from: {0}:{1}'.format(self.client_address[0],self.client_address[1]))
        while(True):
            data = self.request.recv(BUFSIZE)
            self.request.sendall(data)
            time.sleep(0.1)
                
    def finish(self):
        print("client {0}:{1} disconnect!".format(self.client_address[0],self.client_address[1]))

def connect():
    HOST = socket.gethostname()
    PORT = 8000
    
    server = ThreadedTCPServer((HOST, PORT), ThreadedTCPRequestHandler)
    server_thread = threading.Thread(target=server.serve_forever)
    server_thread.start()
    print('Server is starting up...')
    print('Host: {0}, listen to port: {1}'.format(HOST,PORT))
            
if __name__=='__main__':
    connect()
    
    
    

Client:

import socket
import time

HOST = '192.168.1.10' #server的ip地址
PORT = 8000

s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.connect((HOST, PORT))
i = 0
while (1):
    s.sendall('This is client a')
    data = s.recv(1024)
    
    print('Received', repr(data))
    i+=1
    time.sleep(2)
s.close()