Python TCPSocket

发布时间:2019-08-30 08:26:48编辑:auto阅读(1678)

    TCP套接字

    TCPSockServer:

    from socket import *
    from time import ctime
    BUFFSISE = 1024
    HOST = '127.0.0.1'
    PORT = 10054
    mySocket = socket(AF_INET, SOCK_STREAM, 0)
    ADDR = (HOST, PORT)
    mySocket.bind(ADDR)
    mySocket.listen(5)
    while True:
        print("waiting for connection...\n")
        clietSocket, clientAddr = mySocket.accept()
        print("recive an request from: ", clientAddr)
        while True:
            data = clietSocket.recv(BUFFSISE).decode()
            print("received data: %s" % data)
            if not data:
                break
            clietSocket.send(('[%s] %s' % (ctime(), data)).encode())
        clietSocket.close()
    mySocket.close()

    TCPSockClient:

    from socket import *
    HOST = '127.0.0.1'
    PORT = 10054
    ADDR = (HOST, PORT)
    BUFFSIZE = 1024
    mySocket = socket(AF_INET, SOCK_STREAM, 0)
    mySocket.connect(ADDR)
    while True:
        data = input(">: ")
        if not data:
            break
        mySocket.send(data.encode())
        data = mySocket.recv(BUFFSIZE)
        if not data:
            break
        print(data)
    mySocket.close()

关键字

上一篇: python学习前期(笔记)

下一篇: Python Redis