首页 > 代码库 > scoket多线程例子
scoket多线程例子
大体思路,有n台mc,要dump出数据,n台进行对比,看数据是否一致,设计到同时dump的问题,server断发条指令给这n台mc,mc同时去dump把结果返回给server端,server端把这些结果进行对比
server段
#!/usr/bin/python
#coding:utf8
import socket
import os
import threading
import time
import sys
def work_1(ip,conn):
global should_stop
while True:
‘‘‘
if should_stop:
print "should_stop"
break
‘‘‘
time.sleep(10)
conn.send(ip)
client_data=http://www.mamicode.com/conn.recv(1024)
data1=client_data.split(" ")[0]
try:
data2=client_data.split(" ")[1]
except IndexError, e:
print "should_stop set"
should_stop = True
bb=open(‘/home/text.txt‘,‘a‘)
bb.write(client_data+‘\n‘)
print time.time(),client_data
s=socket.socket(socket.AF_INET,socket.SOCK_STREAM)
s.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
s.bind((‘10.13.144.224‘,9999))
s.listen(10)
s.setblocking(0)
s.settimeout(10)
ip=‘10.13.144.224‘
list_1=[]
should_stop = False
while True:
if should_stop: break
try:
conn,addr=s.accept()
except socket.timeout:
continue
print "client timeout: ",conn.gettimeout()
a=0
aa=threading.Thread(target=work_1,args=(ip,conn))
list_1.append(aa)
print list_1
aa.start()
print "join"
for i in list_1:
i.join()
print ‘+++++‘
cc=open(‘/home/text.txt‘,‘r‘)
cd=open(‘/home/text1.txt‘,‘w‘)
ca=cc.readlines()
for ii in ca:
if ii == ‘‘:
break
elif ii == ‘\n‘:
pass
else:
cd.write(ii)
cd.close()
cg=open(‘/home/text1.txt‘,‘r‘)
cf=cg.readlines()
dict_1={}
for iiii in cf:
print ‘ok‘
dict_1[iiii.split(" ")[0]]=iiii.split(" ")[1]
print dict_1
print int(dict_1[dict_1.keys()[0]])-int(dict_1[dict_1.keys()[1]])
cz=open(‘/home/text.txt‘,‘w‘)
cz.truncate()
cy=open(‘/home/text1.txt‘,‘w‘)
cy.truncate()
print ‘exit‘
client断
#!/usr/bin/python
#coding:utf8
import socket
import time
import telnetlib
def mem_status(ip,port):
print ip
print port
tn=telnetlib.Telnet(ip,port)
tn.set_debuglevel(1)
tn.write(‘dump /data0/logs/b.log‘+‘\n‘)
tn.write(‘quit‘+‘\n‘)
return ‘ok‘
def work_lines(file):
print file
open_file=open(file,‘r‘)
print open_file
file_lines=open_file.readlines()
return file_lines
c=socket.socket(socket.AF_INET,socket.SOCK_STREAM)
c.connect((‘10.13.144.224‘,9999))
file=‘/data0/logs/b.log‘
rec=c.recv(1024)
if rec == ‘10.13.144.224‘:
return_value=http://www.mamicode.com/mem_status(‘10.67.15.11‘,22224)
time.sleep(10)
if return_value:
a=open(‘/data0/logs/b.log‘,‘r‘)
file_lines=a.readlines()
over=‘10.67.15.11‘+‘ ‘+str(len(file_lines))
print over
#over=‘10.13.144.224‘,str(len(file_lines))
c.send(str(over))
本文出自 “expect批量同步数据” 博客,请务必保留此出处http://4249964.blog.51cto.com/4239964/1557426
scoket多线程例子