취미 학습python3(40)-TCP 서버와 클라이언트(socketserver 클래스)

#!/usr/bin/env python3

import socket
import sys

HOST="localhost"
PORT=21200
ADDR=(HOST,PORT)

# Create a socket (SOCK_STREAM means a TCP socket)
with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as sock:
    #  
    sock.connect(ADDR)
    data=input('==>')
    sock.sendall(bytes(data + "
", "utf-8")) # Receive data from the server and shut down received = str(sock.recv(1024), "utf-8") print("Sent: {}".format(data)) print("Received: {}".format(received)) #!/usr/bin/env python3 import socketserver from time import ctime HOST='' PORT=21200 ADDR=(HOST,PORT) class MyTCPHandler(socketserver.StreamRequestHandler): def handle(self): print(" {0} ...".format(self.client_address)) self.data = self.rfile.readline().strip() print("{} :".format(self.client_address[0])) print(self.data) # self.wfile , self.wfile.write(bytes("{0}:{1} ".format(ctime(),self.data),'utf-8')) if __name__ == "__main__": # Create the server, binding to localhost on port 9999 with socketserver.TCPServer(ADDR, MyTCPHandler) as server: print(" ...") # , ctrl+c server.serve_forever()

bogon:python3 myhaspl$python3 1-c.py ==>hhh Sent: hhh Received: Sun Sep 16 12:47:01 2018:b'hhh'아래는 서버 측 운행 상태:
연결을 기다리며... 연결을 받다 ('127.0.0.1', 50751) 연결... 127.0.0.1 메시지를 보내다: b'hi'수용('127.0.0.1', 50752) 연결... 127.0.0.1 메시지를 보내다: b'hhh'

좋은 웹페이지 즐겨찾기