python实现socket分布式通信系统
服务器
#!/usr/bin/python
# -*- coding: UTF-8 -*-
from socket import *
import threading
import time
import pymysql
PiID = 1
adjID = [2,3,4]
HOST = ''
PORT = 6661
BUFSIZ = 1024
ADDR = (HOST,PORT)
print('节点ID:', PiID)
print('邻居节点:', adjID)
class MyThread (threading.Thread):
def __init__(self, threadID, name, counter):
threading.Thread.__init__(self)
self.threadID = threadID
self.name = name
self.counter = counter
#def run(self):
#print("Starting " + self.name)
print_time(self.name, self.counter, 1)
def print_time(threadName, delay, counter):
while counter:
time.sleep(delay)
print ("Client %s: %s" % (threadName, time.ctime(time.time())))
counter -= 1
def data_recv():
while True:
global client_data
client_data = client_sock.recv(1024).decode(encoding='utf-8')
print ('客户端接收:',client_data)
return client_data
def mysql_connect():
db = pymysql.connect("localhost", "root", "123", "pi10") # 连接数据库
cursor = db.cursor() # 获取光标
sql = client_data
print (sql)
try:
cursor.execute(sql)
db.commit()
except:
db.rollback()
data = cursor.fetchall()
#print(list(data))
for i in data:
print(i)
#client_sock.send(str(data).encode(encoding='utf-8'))
#client_sock.close()
def send():
try:
print(PiID)
client_sock.send(bytes(PiID))
except:
print('~error~')
ClientConnected = 0
threads = []
while True:
server_sock = socket(AF_INET, SOCK_STREAM)
server_sock.setsockopt(SOL_SOCKET, SO_KEEPALIVE, 1)
server_sock.bind(ADDR)
server_sock.listen(5)
print ('waiting for connection...')
client_sock,client_addr = server_sock.accept()
if 1:
print ('...connected from: ',client_addr[0])
ClientConnected += 1
try:
temp = MyThread(ClientConnected, ClientConnected, 1)#线程函数可以根据需求自己扩展
temp.start()
threads.append(temp)
t1 = threading.Thread(target=data_recv, args=())
t2 = threading.Thread(target=mysql_connect, args=())
t3 = threading.Thread(target=send, args=())
t1.start()
t3.start()
t2.start()
threads.append(t1)
time.sleep(3)
except:
print ("error, thread")
print ("Exiting Main Thread")