Python TCP Client 客戶端程式 (定時傳送資料)
#!/usr/bin/env python3
'''
TCP Client 的流程分為以下幾大步驟:
建立 socket:s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
連線至遠端地址:s.connect()
傳送資料:s.send()、s.sendall()
接收資料:s.recv()
傳輸完畢後,關閉 socket:s.close()
'''
# -*- coding: utf-8 -*-
import socket
import time
HOST = '127.0.0.1'
PORT = 7002
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.connect((HOST, PORT))
i=0
while True:
i=i+1
outdata = 'heartbeat' + str(i)
print('send: ' + outdata)
s.send(outdata.encode())
indata = s.recv(1024)
if len(indata) == 0: # connection closed
s.close()
print('server closed connection.')
break
print('recv: ' + indata.decode())
time.sleep(2)
沒有留言:
張貼留言