1. 程式人生 > >【Python】TCP網路程式設計

【Python】TCP網路程式設計

【Python TCP網路使用】


注意: 必須先啟動伺服器!!!不然會報錯

import socket;

def LanJian_TcpClient():
    with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as s:
        s.connect((socket.gethostname(), 10010))

        while True:
            bufsnd = 'HelloWorld Python Tcp !\r\n'
            s.send(bufsnd.encode("utf-8"))
            bufrv = s.recv(1024)
            if bufrv.decode('utf-8') == 'end':
                break
            print(bufrv.decode('utf-8'))
    s.close()
    return

def LanJian_TcpServer():
    s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
    host = socket.gethostname()
    port = 10011
    s.bind((host, port))
    s.listen(5)
    client, addr = s.accept()
    print(addr, 'connected...')

    while True:
        bufrv = client.recv(1024)
        if bufrv.decode("utf-8") == "end":
            break
        print(bufrv.decode('utf-8'))

    s.close()
    print("close...")
    return

LanJian_TcpClient()
# LanJian_TcpServer()