Python client server socket send and recv problems - python

I have successful sending and receiving between test_client and test_server for a few sends and receives. But when I input more than 4 or 5 data and click enter after each at the input() function the program hangs. I think I've narrowed the problem down to likely be either the rdt_rcv() or udt_send() function. I've highlighted with comments the rdt_rcv() function for both sender and receiver and added a comment above the udt_send() function. But I can't see what's wrong with the functions. Of course it could be something else but I think the problem is one of the two functions I mentioned above. Try running the programs by running test_server first and test_client second with rdt.py in the same folder as the 2 test modules.
test_client.py
import socket, rdt, sys
TCP_IP = 'localhost'
TCP_PORT = 10000
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.connect((TCP_IP, TCP_PORT))
InitialSeqNumber = 0
NextSeqNum = InitialSeqNumber
SendBase = InitialSeqNumber
while 1:
d = input("Input data: ")
data = rdt.rdt_send(d)
data = int(data)
if rdt.rdt_send_called == 1:
checksum = 0xFFFF - data # Assuming 28 byte data
sndpkt = rdt.packet(NextSeqNum, 0, checksum, data)
rdt.udt_send(sndpkt, s)
NextSeqNum = NextSeqNum + sys.getsizeof(data)
#####################################
seq, ack, check, dat = rdt.rdt_rcv(s)
#####################################
rdt.rdt_send_called = 0
print ("Sequence Number: " + str(seq))
print ("ACK Number: " + str(ack))
print ("Checksum Value: " + hex(check))
print ("Data: " + str(dat))
print ('\n')
s.close()
rdt.py
rdt_send_called = None
timeout_event = None
ACK_received = None
BUFFER_SIZE = 1024
class packet:
def __init__(self, seq_num, ack_num, checksum, data):
self.seq_num = seq_num
self.ack_num = ack_num
self.checksum = checksum
self.data = data
def rdt_send(data):
d = data
global rdt_send_called
rdt_send_called = 1
return d
# PROBLEM MAY BE WITH THIS FUNCTION
def udt_send(sndpkt, s):
s.send((str(sndpkt.seq_num)).encode())
s.send((str(sndpkt.ack_num)).encode())
s.send((str(sndpkt.checksum)).encode())
s.send((str(sndpkt.data)).encode())
# PROBLEM IS MOST LIKELY WITH THIS FUNCTION
def rdt_rcv(conn):
field1 = conn.recv(BUFFER_SIZE)
field1 = int(field1)
field2 = conn.recv(BUFFER_SIZE)
field2 = int(field2)
#if field2 != 0:
#global ACK_received
#ACK_received = 1
field3 = (conn.recv(BUFFER_SIZE))
field3 = int(field3)
field4 = (conn.recv(BUFFER_SIZE))
field4 = int(field4)
return field1, field2, field3, field4
def deliver_data(data):
pass
def timeout():
global timeout_event
timeout_event = 1
test_server.py
import socket, rdt, sys
TCP_IP = '127.0.0.1'
TCP_PORT = 10000
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
s.bind((TCP_IP, TCP_PORT))
s.listen(1)
conn, addr = s.accept()
while 1:
dont_send_ACK = 0
#####################################################
seq_num, ack_num, check_sum, data = rdt.rdt_rcv(conn)
#####################################################
print ("Sequence Number: " + str(seq_num))
print ("ACK number: " + str(ack_num))
print ("Checksum Value: " + hex(check_sum))
print ("Data: " + hex(data))
print ('\n')
if data + check_sum != 0xFFFF:
dont_send_ACK = 1 # sender will timeout
else:
rdt.deliver_data(data)
if dont_send_ACK == 0:
ACK = seq_num + sys.getsizeof(data)
checksum = 0xFFFF - ACK
sndpkt = rdt.packet(0, ACK, checksum, 0)
rdt.udt_send(sndpkt, conn)
conn.close()

Related

What does a null traceback mean?

I am testing some scripts, and i found a null error traceback on the client script:
=========== RESTART: /home/pi/Desktop/Pythonic/Chat/ReadClient.py ===========
Enter name: SuperUser
Enter server port: 5162
> Traceback (most recent call last):
I have no idea what this means, and here are both the scripts:
What i am thinking is, the python default IDE thinks it found an error, but it does not recognize this error type. So it returns a null traceback.
Client script
import os, threading
from socket import *
name = input('Enter name: ')
bufsiz = 1024
host = 'localhost'
port = int(input('Enter server port: '))
addr = (host, port)
client = socket(AF_INET , SOCK_STREAM)
##try:
client.connect(addr)
##except socket_error as serr:
## if serr.errno != errno.ECONNREFUSED:
## raise serr
## else:
## print('Invalid Port number:[111]')
## port = int(input('Enter server port: '))
## addr = (host, port)
## client.connect(addr)
# sending name
client.sendto(name.encode('utf-8'),addr)
os.system('cls' if os.name == 'nt' else 'clear')
def input_loop():
global data, client
while True:
data = input('> ')
if not data:
client.sendto('/disconnect'.encode('utf-8'),addr)
break
else:
client.sendto(data.encode('utf-8'),addr)
def recv_loop(client,caddr):
while True:
data = client.recv(1024).decode('utf-8')
if data != 'n_dat':
if data != '/ping':
print(data)
else:
client.sendto('/ping'.encode('utf-8'),caddr)
print('pinged by server')
threads = []
dat_thread = threading.Thread(target=input_loop, args=())
dat_thread.start()
thread = threading.Thread(target=recv_loop, args=(client,caddr))
thread.start()
Server Script:
import os, socket, time, threading, random
class Server:
def __init__(self,host,port,user):
self.port = port
self.host = host
self.user = user
self.bufsize = 1024
self.addr = (host,port)
self.socket = socket.socket(socket.AF_INET , socket.SOCK_STREAM)
self.socket.bind(self.addr)
print("Server running on",host,"at port",port)
self.socket.listen(5)
class rank:
def __init__(self, level):
self.level = level
def getPerms(l):
return (l==6,l>=6,True,l>=3,l>=2,l>=5,l>=4,l>=3,l>=2,l>=5>l>=6)
def getPerms(level,action):
return getperms(level)[action]
def getLevel(level):
if(level == 1):
return 'Guest'
if(level == 2):
return 'Experienced'
if(level == 3):
return 'Veteran'
if(level == 4):
return 'Donor'
if(level == 5):
return 'Mod'
if(level == 6):
return 'Admin'
if(level == 7):
return 'Owner'
else:
return False
# level scale
# A = Server control
# B = Ban
# C = Chat
# D = Direct Message
# H = Vanish
# I = ignore
# K = Kick
# M = Server mute
# T = Title
# V = View members
# U = Unban
## A B C D I K M T V H U
## _____________________________________
## 1 | Guest | | |X| | | | | | | | |
## 2 | Experienced | | |X| |X| | | |X| | |
## 3 | Veteran | | |X|X|X| | |X|X| | |
## 4 | Donor | | |X|X|X| |X|X|X|X| |
## 5 | Mod | | |X|X|X|X|X|X|X|X| |
## 6 | Admin | |X|X|X|X|X|X|X|X|X|X|
## 7 | Owner |X|X|X|X|X|X|X|X|X|X|X|
## ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
def recv_loop(server,client,caddr):
print ('Connected To',caddr)
while True:
global clients
global ping_count
name = clients[client]
data = client.recv(1024)
namecheck = getrank(caddr[0],name,)
formattime = time.strftime(time.strftime("%H:%M:%S",time.gmtime()))
if not data:
break
if data.decode('utf-8') == '/disconnect':
print(formattime + ' : ' +'[' + namecheck + ']'+ name +' has disconnected ')
break
if data.decode('utf-8') == '/ping':
pings = 0
mssg = str(formattime + ' : ' +'[' + namecheck + ']'+ name +': '+ data.decode('utf-8'))
print(formattime + ' : ' +'[' + namecheck + ']'+ name +': '+ data.decode('utf-8'))
for c in clients:
if c != client:
c.send(mssg.encode('utf-8'))
else:
c.send(bytes('n_dat','utf-8'))
log(name, data.decode('utf-8'),getrank(caddr[0],name))
client.close()
def log(name, msg, rank):
with open('log.txt', 'a') as log:
log.write(time.strftime("%Y-%m-%d %H:%M:%S",time.gmtime())+ ' ' + name + ': ' + msg + '\n')
def getrank(ip, name):
with open('ranks.txt', 'r') as ranks:
for line in ranks:
addr = line.split('$',1)[0]
if addr == ip:
rank = (line.split('$$',1)[0]).split('$')[1]
return rank
print('new user')
writerank(ip,name)
return ' Guest '
def writerank(ip,name):
with open('ranks.txt','a') as file:
file.write(ip + '$' + ' Guest ' + '$$' + name + '$$$' + '0/n')
def ping(client, ping_rate):
global ping_count
while True:
time.sleep(60/ping_rate)
client.send(bytes('/ping','utf-8'))
print('pinging client ' + str(client))
ping_count = ping_count + 1
##def getname(caddr):
## with open('ranks.txt', 'r+') as ranks:
## for line in ranks:
## addr = line.split(' .R. ')[0]
## if addr == caddr:
## name = line.split(' ... ')[1]
## return bytes(name,'utf-8')
##
host = 'localhost'
port = random.randint(5000,6000)
user = 'No one'
name = input('Server name : ')
ping_rate = 6
server = Server(host, port, user)
clients = {}
threads = []
ping_count = 0
while True:
client, caddr = server.socket.accept()
# name extraction
name = client.recv(1024)
#name = getname(caddr)
clients[client] = name.decode('utf-8')
pingthread = threading.Thread(target=ping, args=(client,ping_rate))
thread = threading.Thread(target=recv_loop, args=(server,client, caddr))
pingthread.start()
thread.start()
Does anyone know why this null trackback is occurring??
And if so, How is it avoided?
I seem to have found the answer:
> Traceback (most recent call last):Hello\
> File "/home/pi/Desktop/Pythonic/Chat/ReadClient.py", line 58, in <module>
thread = threading.Thread(target=recv_loop, args=(client,caddr))
Uhh
> NameError: name 'caddr' is not defined
So, as it turns out, the traceback is three separate print functions, but as i have an input loop going, it delayed the print until the input is satisfied
How to reproduce:
import threading
def InputThread():
global data
while True:
data = input('> ')
inputThread = thread.Thread(target=InputThread,args=())
inputThread.start()
raise Exception

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()

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 "----------"

Using Pack instead of Pack_into in Python 2.4.3

The following code is for simulating a Modbus interface on an embedded device. Unfortunely, it has an older Python (2.4.3). The code works on 2.7, but not 2.4.3 because the the version Python I am using does not support struct.pack_into, only struct.pack. Could I get some advice on how to fix this? I think I need to use a string maybe and convert to a byte buffer. This talks to non-Python code, so pickle can not be used I believe.
import socket
import sys
import array
import struct
def hexdump(src, length=16):
FILTER = ''.join([(len(repr(chr(x))) == 3) and chr(x) or '.' for x in range(256)])
lines = []
for c in xrange(0, len(src), length):
chars = src[c:c+length]
hex = ' '.join(["%02x" % ord(x) for x in chars])
printable = ''.join(["%s" % ((ord(x) <= 127 and FILTER[ord(x)]) or '.') for x in chars])
lines.append("%04x %-*s %s\n" % (c, length*3, hex, printable))
return ''.join(lines)
HOST = '192.168.1.187'
PORT = 502
s = socket.socket(socket.AF_INET,socket.SOCK_STREAM)
s.bind((HOST,PORT))
s.listen(1)
conn, addr = s.accept()
data = []
datatran = array.array('B', '\x00' * 14)
data = conn.recv(1024)
print 'Connect by', addr
while (data):
sys.stdout.write(hexdump(data))
TransID , ProtoColID, PacketLength, UnitID, FC, StartAddress, RegisterCount = struct.unpack_from(">hhhBBhh", data)
print TransID, ProtoColID, PacketLength, UnitID
print FC, StartAddress, RegisterCount
struct.pack_into(">hhhBBBh", datatran, 0, TransID , ProtoColID, PacketLength+2, UnitID, FC, 2, 51)
conn.sendall(datatran)
data = conn.recv(1024)
conn.close()
s.close()
Thanks
With a bit of size calculation it should be possible to use pack and unpack instead:
import socket
import sys
import array
import struct
def hexdump(src, length=16):
FILTER = ''.join([(len(repr(chr(x))) == 3) and chr(x) or '.' for x in range(256)])
lines = []
for c in xrange(0, len(src), length):
chars = src[c:c+length]
hex = ' '.join(["%02x" % ord(x) for x in chars])
printable = ''.join(["%s" % ((ord(x) <= 127 and FILTER[ord(x)]) or '.') for x in chars])
lines.append("%04x %-*s %s\n" % (c, length*3, hex, printable))
return ''.join(lines)
HOST = '192.168.1.187'
PORT = 502
s = socket.socket(socket.AF_INET,socket.SOCK_STREAM)
s.bind((HOST,PORT))
s.listen(1)
conn, addr = s.accept()
datatranStruct = '>hhhBBBh'
datatranStructSize = struct.calcsize(datatranStruct)
datatranFormat = '%s%dx' % (datatranStruct, 14 - datatranStructSize)
recvStruct = '>hhhBBhh'
recvStructSize = struct.calcsize(recvStruct)
data = conn.recv(1024)
print 'Connect by', addr
while (data):
sys.stdout.write(hexdump(data))
recvFormat = '%s%dx' % (recvStruct, len(data) - recvStructSize)
TransID , ProtoColID, PacketLength, UnitID, FC, StartAddress, RegisterCount = struct.unpack(recvFormat, data)
print TransID, ProtoColID, PacketLength, UnitID
print FC, StartAddress, RegisterCount
datatran = struct.pack(datatranFormat, TransID , ProtoColID, PacketLength+2, UnitID, FC, 2, 51)
conn.sendall(datatran)
data = conn.recv(1024)
conn.close()
s.close()

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