mpi4py: Process communication with 4 processes deadlocks - python

I'm writing a program which should add chars to strings in three different processes. If the resulting string matches a given one, the process which has the match, should send an "endflag" to process 0. After process 0 receives the "endflag" he should send a broadcast to all other processes (1 - 3) and exit. The other processes receive the broadcast and should exit too / stop working.
[...]
string_given = "abc"
magic_bytes = "0xDEA7C0DE"
chars = 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ1234567890 !?#/\%&.-_:,;*+<>|(){}'
end_all = None
if rank == 0:
while(True):
recv_data = comm.recv(source=MPI.ANY_SOURCE)
print("0.recv: %s" % (recv_data))
if recv_data == magic_bytes:
end_all = magic_bytes
send_data = bcast(end_all, root=0)
sys.exit()
if rank == 1:
min, max = 1, 2
while(True):
for n in xrange(min, max):
for c in itertools.product(chars, repeat=n):
string = ''.join(c)
print("1.string: %s" % (string))
if string == string_given:
print("1.found: %s = %s" % (string, string_given))
end_all = magic_bytes
comm.send(end_all, dest=0)
recv_data = comm.bcast(end_all, root=0)
if recv_data == magic_bytes:
sys.exit()
if rank == 2:
min, max = 3, 4
while(True):
for n in xrange(min, max):
for c in itertools.product(chars, repeat=n):
string = ''.join(c)
print("2.string: %s" % (string))
if string == string_given:
print("2.found: %s = %s" % (string, string_given))
end_all = magic_bytes
comm.isend(end_all, dest=0)
recv_data = comm.bcast(end_all, root=0)
if recv_data == magic_bytes:
sys.exit()
[...]
The code above produces following output:
3.string: aaaaa
1.string: a
2.string: aaa
And then i think it deadlocks.
How can i prevent my code from the deadlock?

Related

Porting a python 2 code to Python 3: ICMP Scan with errors

import random
import socket
import time
import ipaddress
import struct
from threading import Thread
def checksum(source_string):
sum = 0
count_to = (len(source_string) / 2) * 2
count = 0
while count < count_to:
this_val = ord(source_string[count + 1]) * 256 + ord(source_string[count])
sum = sum + this_val
sum = sum & 0xffffffff
count = count + 2
if count_to < len(source_string):
sum = sum + ord(source_string[len(source_string) - 1])
sum = sum & 0xffffffff
sum = (sum >> 16) + (sum & 0xffff)
sum = sum + (sum >> 16)
answer = ~sum
answer = answer & 0xffff
answer = answer >> 8 | (answer << 8 & 0xff00)
return answer
def create_packet(id):
header = struct.pack('bbHHh', 8, 0, 0, id, 1)
data = 192 * 'Q'
my_checksum = checksum(header + data)
header = struct.pack('bbHHh', 8, 0, socket.htons(my_checksum), id, 1)
return header + data
def ping(addr, timeout=1):
try:
my_socket = socket.socket(socket.AF_INET, socket.SOCK_RAW, socket.IPPROTO_ICMP)
except Exception as e:
print (e)
packet_id = int((id(timeout) * random.random()) % 65535)
packet = create_packet(packet_id)
my_socket.connect((addr, 80))
my_socket.sendall(packet)
my_socket.close()
def rotate(addr, file_name, wait, responses):
print ("Sending Packets", time.strftime("%X %x %Z"))
for ip in addr:
ping(str(ip))
time.sleep(wait)
print ("All packets sent", time.strftime("%X %x %Z"))
print ("Waiting for all responses")
time.sleep(2)
# Stoping listen
global SIGNAL
SIGNAL = False
ping('127.0.0.1') # Final ping to trigger the false signal in listen
print (len(responses), "hosts found!")
print ("Writing File")
hosts = []
for response in sorted(responses):
ip = struct.unpack('BBBB', response)
ip = str(ip[0]) + "." + str(ip[1]) + "." + str(ip[2]) + "." + str(ip[3])
hosts.append(ip)
file = open(file_name, 'w')
file.write(str(hosts))
print ("Done", time.strftime("%X %x %Z"))
def listen(responses):
global SIGNAL
s = socket.socket(socket.AF_INET, socket.SOCK_RAW, socket.IPPROTO_ICMP)
s.bind(('', 1))
print ("Listening")
while SIGNAL:
packet = s.recv(1024)[:20][-8:-4]
responses.append(packet)
print ("Stop Listening")
s.close()
SIGNAL = True
responses = []
ips = '200.131.0.0/20' # Internet network
wait = 0.002 # Adjust this based in your bandwidth (Faster link is Lower wait)
file_name = 'log1.txt'
ip_network = ipaddress.ip_network(unicode(ips), strict=False)
t_server = Thread(target=listen, args=[responses])
t_server.start()
t_ping = Thread(target=rotate, args=[ip_network, file_name, wait, responses])
t_ping.start()
I tried:
ip_network = ipaddress.ip_network( ips, strict=False) instead of ip_network = ipaddress.ip_network(unicode(ips), strict=False)
because of the error: ""NameError: name 'unicode' is not defined"
after:
I got: my_checksum = checksum(header + data) -> TypeError: can't concat bytes to str
so I tried:
data = bytes(192 * 'Q').encode('utf8') instead of data = 192 * 'Q'
Now, the error is : ""data = bytes (192 * 'Q').encode('utf8') TypeError: string argument without an encoding"
Could anyone help me to port the code to Python 3 ?
import random
import socket
import time
import ipaddress
import struct
from threading import Thread
def checksum(source_string):
sum = 0
count_to = (len(source_string) / 2) * 2
count = 0
while count < count_to:
this_val = source_string[count + 1] * 256 + source_string[count]
sum = sum + this_val
sum = sum & 0xffffffff
count = count + 2
if count_to < len(source_string):
sum = sum + source_string[len(source_string) - 1]
sum = sum & 0xffffffff
sum = (sum >> 16) + (sum & 0xffff)
sum = sum + (sum >> 16)
answer = ~sum
answer = answer & 0xffff
answer = answer >> 8 | (answer << 8 & 0xff00)
return answer
def create_packet(id):
header = struct.pack('bbHHh', 8, 0, 0, id, 1)
data = 192 * b'Q'
my_checksum = checksum(header + data)
header = struct.pack('bbHHh', 8, 0, socket.htons(my_checksum), id, 1)
return header + data
def ping(addr, timeout=1):
try:
my_socket = socket.socket(socket.AF_INET, socket.SOCK_RAW, socket.IPPROTO_ICMP)
except Exception as e:
print (e)
packet_id = int((id(timeout) * random.random()) % 65535)
packet = create_packet(packet_id)
my_socket.connect((addr, 80))
my_socket.sendall(packet)
my_socket.close()
def rotate(addr, file_name, wait, responses):
print ("Sending Packets", time.strftime("%X %x %Z"))
for ip in addr:
ping(str(ip))
time.sleep(wait)
print ("All packets sent", time.strftime("%X %x %Z"))
print ("Waiting for all responses")
time.sleep(2)
# Stoping listen
global SIGNAL
SIGNAL = False
ping('127.0.0.1') # Final ping to trigger the false signal in listen
print (len(responses), "hosts found!")
print ("Writing File")
hosts = set()
for response in sorted(responses):
ip = struct.unpack('BBBB', response)
ip = str(ip[0]) + "." + str(ip[1]) + "." + str(ip[2]) + "." + str(ip[3])
hosts.add(ip)
with open(file_name, 'w') as file:
file.write('\n'.join(sorted(hosts, key=lambda item: socket.inet_aton(item))))
print ("Done", time.strftime("%X %x %Z"))
def listen(responses):
global SIGNAL
s = socket.socket(socket.AF_INET, socket.SOCK_RAW, socket.IPPROTO_ICMP)
s.bind(('', 1))
print ("Listening")
while SIGNAL:
packet = s.recv(1024)[:20][-8:-4]
responses.append(packet)
print ("Stop Listening")
s.close()
SIGNAL = True
responses = []
ips = '192.168.1.0/28' # Internet network
wait = 0.002 # Adjust this based in your bandwidth (Faster link is Lower wait)
file_name = 'log1.txt'
ip_network = ipaddress.ip_network(ips, strict=False)
t_server = Thread(target=listen, args=[responses])
t_server.start()
t_ping = Thread(target=rotate, args=[ip_network, file_name, wait, responses])
t_ping.start()

Attribute Type Invalid PyKCS11

I have python script that essentially mirrors what this Attribute Dump achieves. In my slot number 2 I have a smart card that is recognized by a card reader. The card contains an RSA keypair and an x509 cert, that can be displayed using openssl. There is no problem with the device reader because the session is opened and proper vendor information is displayed, along with [1] object found. While trying to get all the attributes available in attempt to sign a message using SHA1, I'm receiving an CKR_ATTRIBUTE_TYPE_INVALID exception. I'm not sure where the bad attribute types occures and I've tried to locate the culprit for quite some time, to no avail.
print "Found %d objects: %s" % (len(objects), [x.value() for x in objects])
#-----------------------------CUTOFF FOR BAD ATTRIBUTE TYPE----------------------------
all_attributes = PyKCS11.CKA.keys()
# only use the integer values and not the strings like 'CKM_RSA_PKCS'
all_attributes = [e for e in all_attributes if isinstance(e, int)]
attributes = [
["CKA_ENCRYPT", PyKCS11.CKA_ENCRYPT],
["CKA_CLASS", PyKCS11.CKA_CLASS],
["CKA_DECRYPT", PyKCS11.CKA_DECRYPT],
["CKA_SIGN", PyKCS11.CKA_SIGN],
["CKA_VERIFY", PyKCS11.CKA_VERIFY],
["CKA_ID", PyKCS11.CKA_ID],
["CKA_MODULUS", PyKCS11.CKA_MODULUS],
["CKA_MODULUS", PyKCS11.CKA_MODULUS],
["CKA_MODULUS_BITS", PyKCS11.CKA_MODULUS_BITS],
["CKA_PUBLIC_EXPONENT", PyKCS11.CKA_PUBLIC_EXPONENT],
["CKA_PRIVATE_EXPONENT", PyKCS11.CKA_PRIVATE_EXPONENT],
]
for o in objects:
print
print (red + "==================== Object: %d ====================" + normal) % o.value()
attributes = session.getAttributeValue(o, all_attributes)
attrDict = dict(zip(all_attributes, attributes))
if attrDict[PyKCS11.CKA_CLASS] == PyKCS11.CKO_PRIVATE \
and attrDict[PyKCS11.CKA_KEY_TYPE] == PyKCS11.CKK_RSA:
m = attrDict[PyKCS11.CKA_MODULUS]
e = attrDict[PyKCS11.CKA_PUBLIC_EXPONENT]
if m and e:
mx = eval('0x%s' % ''.join(chr(c) for c in m).encode('hex'))
ex = eval('0x%s' % ''.join(chr(c) for c in e).encode('hex'))
if sign:
try:
toSign = "12345678901234567890" # 20 bytes, SHA1 digest
print "* Signing with object 0x%08X following data: %s" % (o.value(), toSign)
signature = session.sign(o, toSign)
s = ''.join(chr(c) for c in signature).encode('hex')
sx = eval('0x%s' % s)
print "Signature:"
print hexdump(''.join(map(chr, signature)), 16)
if m and e:
print "Verifying using following public key:"
print "Modulus:"
print hexdump(''.join(map(chr, m)), 16)
print "Exponent:"
print hexdump(''.join(map(chr, e)), 16)
decrypted = pow(sx, ex, mx) # RSA
print "Decrypted:"
d = hexx(decrypted).decode('hex')
print hexdump(d, 16)
if toSign == d[-20:]:
print "*** signature VERIFIED!\n"
else:
print "*** signature NOT VERIFIED; decrypted value:"
print hex(decrypted), "\n"
else:
print "Unable to verify signature: MODULUS/PUBLIC_EXP not found"
except:
print "Sign failed, exception:", str(sys.exc_info()[1])
if decrypt:
if m and e:
try:
toEncrypt = "12345678901234567890"
# note: PKCS1 BT2 padding should be random data,
# but this is just a test and we use 0xFF...
padded = "\x00\x02%s\x00%s" % ("\xFF" * (128 - (len(toEncrypt)) - 3), toEncrypt)
print "* Decrypting with 0x%08X following data: %s" % (o.value(), toEncrypt)
print "padded:\n", dump(padded, 16)
encrypted = pow(eval('0x%sL' % padded.encode('hex')), ex, mx) # RSA
encrypted1 = hexx(encrypted).decode('hex')
print "encrypted:\n", dump(encrypted1, 16)
decrypted = session.decrypt(o, encrypted1)
decrypted1 = ''.join(chr(i) for i in decrypted)
print "decrypted:\n", dump(decrypted1, 16)
if decrypted1 == toEncrypt:
print "decryption SUCCESSFULL!\n"
else:
print "decryption FAILED!\n"
except:
print "Decrypt failed, exception:", str(sys.exc_info()[1])
else:
print "ERROR: Private key don't have MODULUS/PUBLIC_EXP"
print "Dumping attributes:"
for q, a in zip(all_attributes, attributes):
if a == None:
# undefined (CKR_ATTRIBUTE_TYPE_INVALID) attribute
continue
if q == PyKCS11.CKA_CLASS:
print format_long % (PyKCS11.CKA[q], PyKCS11.CKO[a], a)
elif q == PyKCS11.CKA_CERTIFICATE_TYPE:
print format_long % (PyKCS11.CKA[q], PyKCS11.CKC[a], a)
elif q == PyKCS11.CKA_KEY_TYPE:
print format_long % (PyKCS11.CKA[q], PyKCS11.CKK[a], a)
elif session.isBin(q):
print format_binary % (PyKCS11.CKA[q], len(a))
if a:
print dump(''.join(map(chr, a)), 16),
elif q == PyKCS11.CKA_SERIAL_NUMBER:
print format_binary % (PyKCS11.CKA[q], len(a))
if a:
print hexdump(a, 16),
else:
print format_normal % (PyKCS11.CKA[q], a)
The bad entry type in the attribute list is somewhere in the code above. I'm not sure which is causing it to fail. I have confused myself after learning the LowLevel API first.
Slot no: 2
slotDescription: ONMIKEY CardMan 3111
manufacturerID: OMNIKEY
TokenInfo
label: SSS Card 001
manufacturerID: Siemens
model: Siem. OS V4.x
Opened session 0x00020001
Found 1 objects: [1]
==================== Object: 1 ====================
Error: CKR_ATTRIBUTE_TYPE_INVALID (0x00000012)
Is the best approach to construct my own attribute list?

how to scan ble device based on the mac address stored in database using python

I am using for loop to get the mac address from database but the loop printed the ble mac address 17 times. I tried using if else to compare the mac address with the mac address stored in database but the output scan nothing. Is there any other way to filter out other ble mac address?
import os
import sys
import struct
import bluetooth._bluetooth as bluez
import MySQLdb
# Open database connection
db = MySQLdb.connect("localhost","DB_USER","DB_PASSWORD","DB_NAME" )
# prepare a cursor object using cursor() method
cursor = db.cursor()
sql = "SELECT * FROM Mac_address"
cursor.execute(sql)
# Fetch all the rows in a list of lists.
results = cursor.fetchall()
for row in results:
NAME = row[0]
mac_address = row[1]
time = row[2]
LE_META_EVENT = 0x3e
LE_PUBLIC_ADDRESS=0x00
LE_RANDOM_ADDRESS=0x01
LE_SET_SCAN_PARAMETERS_CP_SIZE=7
OGF_LE_CTL=0x08
OCF_LE_SET_SCAN_PARAMETERS=0x000B
OCF_LE_SET_SCAN_ENABLE=0x000C
OCF_LE_CREATE_CONN=0x000D
LE_ROLE_MASTER = 0x00
LE_ROLE_SLAVE = 0x01
# these are actually subevents of LE_META_EVENT
EVT_LE_CONN_COMPLETE=0x01
EVT_LE_ADVERTISING_REPORT=0x02
EVT_LE_CONN_UPDATE_COMPLETE=0x03
EVT_LE_READ_REMOTE_USED_FEATURES_COMPLETE=0x04
# Advertisment event types
ADV_IND=0x00
ADV_DIRECT_IND=0x01
ADV_SCAN_IND=0x02
ADV_NONCONN_IND=0x03
ADV_SCAN_RSP=0x04
def returnnumberpacket(pkt):
myInteger = 0
multiple = 256
for c in pkt:
myInteger += struct.unpack("B",c)[0] * multiple
multiple = 1
return myInteger
def returnstringpacket(pkt):
myString = "";
for c in pkt:
myString += "%02x" %struct.unpack("B",c)[0]
return myString
def printpacket(pkt):
for c in pkt:
sys.stdout.write("%02x " % struct.unpack("B",c)[0])
def get_packed_bdaddr(bdaddr_string):
packable_addr = []
addr = bdaddr_string.split(':')
addr.reverse()
for b in addr:
packable_addr.append(int(b, 16))
return struct.pack("<BBBBBB", *packable_addr)
def packed_bdaddr_to_string(bdaddr_packed):
return ':'.join('%02x'%i for i in struct.unpack("<BBBBBB", bdaddr_packed[::-1]))
def hci_enable_le_scan(sock):
hci_toggle_le_scan(sock, 0x01)
def hci_disable_le_scan(sock):
hci_toggle_le_scan(sock, 0x00)
def hci_toggle_le_scan(sock, enable)
cmd_pkt = struct.pack("<BB", enable, 0x00)
bluez.hci_send_cmd(sock, OGF_LE_CTL, OCF_LE_SET_SCAN_ENABLE, cmd_pkt)
def hci_le_set_scan_parameters(sock):
old_filter = sock.getsockopt( bluez.SOL_HCI, bluez.HCI_FILTER, 14)
SCAN_RANDOM = 0x01
OWN_TYPE = SCAN_RANDOM
SCAN_TYPE = 0x01
def parse_events(sock, loop_count=100):
old_filter = sock.getsockopt( bluez.SOL_HCI, bluez.HCI_FILTER, 14)
# perform a device inquiry on bluetooth device #0
# The inquiry should last 8 * 1.28 = 10.24 seconds
# before the inquiry is performed, bluez should flush its cache of
# previously discovered devices
flt = bluez.hci_filter_new()
bluez.hci_filter_all_events(flt)
bluez.hci_filter_set_ptype(flt, bluez.HCI_EVENT_PKT)
sock.setsockopt( bluez.SOL_HCI, bluez.HCI_FILTER, flt )
done = False
results = []
myFullList = []
for i in range(0, loop_count):
pkt = sock.recv(255)
ptype, event, plen = struct.unpack("BBB", pkt[:3])
#print "--------------"
if event == bluez.EVT_INQUIRY_RESULT_WITH_RSSI:
i =0
elif event == bluez.EVT_NUM_COMP_PKTS:
i =0
elif event == bluez.EVT_DISCONN_COMPLETE:
i =0
elif event == LE_META_EVENT:
subevent, = struct.unpack("B", pkt[3])
pkt = pkt[4:]
if subevent == EVT_LE_CONN_COMPLETE:
le_handle_connection_complete(pkt)
elif subevent == EVT_LE_ADVERTISING_REPORT:
#print "advertising report"
num_reports = struct.unpack("B", pkt[0])[0]
report_pkt_offset = 0
for i in range(0, num_reports):
Mac = packed_bdaddr_to_string(pkt[report_pkt_offset + 3:report_pkt_offset + 9])
for Mac in row[1]:
print "-------------"
#print "\tfullpacket: ", printpacket(pkt)
print "\tMAC address: ", row[1] # commented out - don't know what this byte is. It's NOT TXPower
txpower, = struct.unpack("b", pkt[report_pkt_offset -2])
print "\t(Unknown):", txpower
rssi, = struct.unpack("b", pkt[report_pkt_offset -1])
print "\tRSSI:", rssi
break
# build the return string
Adstring = packed_bdaddr_to_string(pkt[report_pkt_offset + 3:report_pkt_offset + 9])
Adstring += ","
Adstring += returnstringpacket(pkt[report_pkt_offset -22: report_pkt_offset - 6])
Adstring += ","
Adstring += "%i" % returnnumberpacket(pkt[report_pkt_offset -6: report_pkt_offset - 4])
Adstring += ","
Adstring += "%i" % returnnumberpacket(pkt[report_pkt_offset -4: report_pkt_offset - 2])
Adstring += ","
Adstring += "%i" % struct.unpack("b", pkt[report_pkt_offset -2])
Adstring += ","
Adstring += "%i" % struct.unpack("b", pkt[report_pkt_offset -1])
#print "\tAdstring=", Adstring
myFullList.append(Adstring)
done = True
sock.setsockopt( bluez.SOL_HCI, bluez.HCI_FILTER, old_filter )
return myFullList
db.close()
The above is save as blescan.py. I run this file below to do a ble scan.
import blescan
import sys
import bluetooth._bluetooth as bluez
dev_id = 0
try:
sock = bluez.hci_open_dev(dev_id)
print "ble thread started"
except:
print "error accessing bluetooth device..."
sys.exit(1)
blescan.hci_le_set_scan_parameters(sock)
blescan.hci_enable_le_scan(sock)
while True:
returnedList = blescan.parse_events(sock, 10)
print "----------"

Python code reading serial inputs on Beaglebone

I am trying to read the data from my Geiger Counter on my Beaglebone, but when I print the result, doesn't include my counter code:
import Adafruit_BBIO.UART as UART
import serial
import time
UART.setup("UART4")
ser = serial.Serial(port = "/dev/ttyO4", baudrate=9600)
r = 0
d = 0
z = 0
minutes = 0
while True:
timeout = time.time() + 60
while True:
x = ser.read()
if ser.isOpen():
print "Serial is open!"
r = r +1
print r
print x
elif x is '0':
d=d+1
#print '.'
elif x is '1':
d=d+1
#print '.'
time.sleep(1)
z=z+d
print "CPM %f " % d
print "total %f" % z
print "minutes %f" % minutes
My output came out as:
Serial is open!
1
1
Serial is open!
2
1
Serial is open!
3
0
There is no break in your inner while loop, so it will loop infinitely. Assuming counter code means the print statements at the end of your code sample, they will never be reached.

Sockets, communication stops

I have a simple question about socket programming. I've done to implement a server and two clients as following codes, but all of sudden it stops while it communicates each other. I have no idea why it happens all the time.
Would you give me advice, hint, or help?
Thank you for your time.
Client
# simple client
import socket
import sys
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
host = ""
port = 12345
buf = 100
s.connect((host, port))
i = 0
timestep = 0
while(1):
k = '01'#+str(timestep)
#1
s.send(k)
print 'sending message is', k
#2
v = s.recv(buf)
print v
if v == 'hold 01':
print 'timestep is', timestep#'send the previous message'
if timestep == 0:
timestep == 0
else:
timestep -= 1
else:
print 'read data'
FILE = open("datainfo1.txt", "r+")
msg = FILE.read()
FILE.close()
#3
while(1):
tmp, msg = msg[:buf], msg[buf:]
s.send(tmp)
print len(tmp)
if len(tmp) < buf:
print 'break'
break
# send file
i+=1
timestep+=1
print 'end'
s.close()
Server
import socket, sys
# set up listening socket
lstn = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
host = ""
port = 12345
# bind lstn socket to this port
lstn.bind(("", port))
lstn.listen(5)
# initialize buffer size
buf = 100
# initialize concatenate string, v
v = ''
# initialize client socket list
cs = []
check = [0, 0]
# a fixed number of clients
nc = 1
count = 0
status = [0,0]
j = 0
step = [0,0]
for i in range(nc):
(clnt,ap) = lstn.accept()
clnt.setblocking(0)
cs.append(clnt)
file = open("output_analysis.txt","w+")
while (len(cs) > 0):
clnt = cs.pop(0)
cs.append(clnt)
try:
#1
k = clnt.recv(buf)
print "k=",k,"\n"#[:2]
if k == '01':
print "1st client connected", status[0]
file.write("1st\t")
if status[0] == 0:
v = 'hold 01'
check[0] = 1
elif status[0] == 1:
v = 'go 01'
# status[0] = 0
print v, "the message\n"
file.write(v)
file.write("\t")
#2
clnt.send(v)
if status[0] == 1:
FILE = open("client1.txt","w+")
print 'receive 01'
#3
while(1):
status[0] = 0
print '1st : receiving'
msg = clnt.recv(buf)
print len(msg)
if len(msg) < buf:
print 'break'
#FILE.close()
break
elif k == '02':
print "2nd client connected", status[0]
file.write("2nd\t")
if status[1] == 0:
v = 'hold 02'
check[1] = 1
elif status[1] == 1:
v = 'go 02'
# status[0] = 0
print v, "the message\n"
file.write(v)
file.write("\t")
#2
clnt.send(v)
if status[1] == 1:
FILE = open("client2.txt","w+")
print 'receive 02'
#3
while(1):
status[1] = 0
print '2nd : receiving'
msg = clnt.recv(buf)
print len(msg)
if len(msg) < buf:
print 'break'
#FILE.close()
break
if check[0] == 1:# and check[1] == 1:
print j, 'here\n'
j += 1
for i in range(2):
check[i] = 0
status[i] = 1 # which means, all clients are connected
print check, status
else:
print 'hello'
except: pass
file.close()
lstn.close()
except: pass
You're ignoring all exceptions. This is a bad idea, because it doesn't let you know when things go wrong. You'll need to remove that except handler before you can reasonably debug your code.
One problem is you are setting non-blocking mode:
clnt.setblocking(0)
But never checking that it is safe to send or recv data. It turns out that since the code is ignoring all exceptions, it isn't seeing the following error that I got when I removed the try:
Exception [Errno 10035] A non-blocking socket operation could not be completed immediately
After removing the setblocking call, the code proceeded further, but still has problems.
Describing what problem you are trying to solve would help to understand what the code is trying to do.

Categories

Resources