2014年3月5日

一個python的socket實例 (Python3)

http://uds.tw/page.php?i=52

一個python的socket實例,我在這裡囑咐自己!!不要在忘記socket傳遞資料時都是以byte來進行的
print('server start...')
if __name__ == '__main__':  
    import socket
    sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
    sock.bind(('127.0.0.1', 8001))  
    sock.listen(5)
    while True:  
        connection,address = sock.accept()
        try:
            connection.settimeout(5)
            buf = connection.recv(1024)
            print(buf.decode("utf-8"))
            s = "哇哈哈"
            connection.send(s.encode('utf-8'))
        except socket.timeout:
            print('time out')
        connection.close()




if __name__ == '__main__':  
    import socket  
    sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)  
    sock.connect(('127.0.0.1', 8001))  

    sock.send('客戶端給伺服器端的訊息文字....'.encode('utf-8'))
    str = sock.recv(1024)
    print(str.decode("utf-8"))
    sock.close()  

沒有留言:

張貼留言