標籤:
1. f1.py
# -*- coding: utf-8 -*-import socketimport structimport sqlalchemyimport pandas########################################################################class sckt: #---------------------------------------------------------------------- def __init__(self, host = ‘192.168.1.3‘, port = 12345): self.host = host self.port = port #---------------------------------------------------------------------- def run_server(self): sckt = socket.socket(socket.AF_INET, socket.SOCK_STREAM) sckt.bind((self.host, self.port)) sckt.listen(5) """串連庫""" engine = sqlalchemy.create_engine(‘mssql+pyodbc://sa:[email protected]‘) """取開盤價""" Open = (pandas.read_sql(‘sh‘, engine))[‘open‘] i = 0 while True: connection, address = sckt.accept() if connection.recv(1024) == b‘Link‘ and i < (len(Open) - 1): """資料打包""" connection.send(struct.pack(‘f‘, Open[i])) i += 1 else: connection.send(b‘Cut off the connection!‘) connection.close() #---------------------------------------------------------------------- def run_client(self, message = b‘Link‘): sckt = socket.socket(socket.AF_INET, socket.SOCK_STREAM) sckt.connect((self.host, self.port)) sckt.send(message) """資料解包,注意 unpack 要求四位元組,其用法為後接 [:4]""" Open = struct.unpack(‘f‘, sckt.recv(1024)[:4]) sckt.close() """返回開盤價,去格式的用法後接 [0]""" return Open[0]
2. f2.py
# -*- coding: utf-8 -*-import syssys.path.append(‘D:/360data/重要資料/案頭‘)import f1F1 = f1.sckt()F1.run_server()Open = []for i in range(0, 99): Open.append(F1.run_client()) print(Open)
Python socket編程之三:類比資料庫迴圈發布資料