socketserver의 간단한 사용 방법

1307 단어
서버 코드
import socketserver

'''
         ,        BaseRequestHandler,           handle()
   TCPServer ,    server ip                  TCPServer
server.handle_request() #       
server.serve_forever() #        ,    
'''

class MyTCPHandler(socketserver.BaseRequestHandler):
    def handle(self):
        while True:
            try:
                self.data = self.request.recv(1024).strip()
                if not self.data:
                    break
                print('     :',self.client_address)
                print('>>>',self.data.decode())
                self.request.send(self.data.upper())
            except ConnectionResetError as e:
                print(e)
                break


if __name__ == '__main__':
    HOST,PORT = 'localhost',8080
    server = socketserver.ThreadingTCPServer((HOST,PORT),MyTCPHandler)
    server.serve_forever()

클라이언트 코드
import socket

client = socket.socket()
client.connect(('localhost',8080))

while True:
    data = input('>>>')
    if not data:
        continue
    client.send(data.encode('utf-8'))#data       

    data = client.recv(1024).decode()
    print('>>>',data)

client.close()

좋은 웹페이지 즐겨찾기