python的socket的tcp協議編程

  1. 服務端代碼以下:

    # _*_ coding:utf-8 _*_
    import socket
    import datetime
    HOST='0.0.0.0'
    PORT=3434socket

    s=socket.socket(socket.AF_INET,socket.SOCK_STREAM)
    s.bind((HOST,PORT))
    s.listen(1)3d

    while True:
    conn,addr=s.accept()
    print 'Client %s connected!'%str(addr)
    dt=datetime.datetime.now()
    message='Current time is'+str(dt)
    conn.send(message)
    print "Sent:",message
    conn.close()blog

  2. 客戶端代碼以下:

    import socket
    HOST='127.0.0.1'
    PORT=3434
    s=socket.socket(socket.AF_INET,socket.SOCK_STREAM)
    s.connect((HOST,PORT))
    print "Connect %s:%d ok"%(HOST,PORT)
    data=s.recv(1024)
    print "Received:",data
    s.close()utf-8

相關文章
相關標籤/搜索