-
Notifications
You must be signed in to change notification settings - Fork 1
/
client.py
105 lines (93 loc) · 2.57 KB
/
client.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
"""
Laptop-side client for database information access and label printing
via TCP/IP communication
Authors: Aparajito Saha and Amulya Khurana
"""
from threading import Thread
import socket, time
from print_manipulation import *
import csv
IP_ADDRESS = '192.168.137.216'
IP_PORT = 65432
class Client():
def run(self):
print("Client started")
while True:
try:
rcvMsg = self.readServerMsg()
except:
print("Exception in Client.run()")
isClientRunning = False
closeConnection()
break
print("Client thread terminated")
def readServerMsg(self):
bufSize = 2048
data = ""
while data[-1:] != "\0": # reply with end-of-message indicator
try:
blk = sock.recv(bufSize)
except:
raise Exception("Exception from blocking sock.recv()")
data += blk.decode('utf-8')
print("Data received:", data)
return data
def sendCommand(data):
print("sendCommand() with msg = " + data)
data = data + "\0"
data = bytes(data, 'utf-8')
try:
# append \0 as end-of-message indicator
sock.sendall(data)
except:
print("Exception in sendCommand()")
closeConnection()
def closeConnection():
global isConnected
print("Closing socket")
sock.close()
isConnected = False
def connect():
global sock
sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
print("Connecting...")
try:
sock.connect((IP_ADDRESS, IP_PORT))
except:
print("Connection failed.")
return False
return True
def read_csv(id):
rows = []
data = open("sample_student_data_read.csv", "r")
csvreader = csv.reader(data)
# extracting each data row one by one
for row in csvreader:
rows.append(row)
for row in rows:
if row[0] == str(id):
return row[2] + " " + row[3]
return ""
sock = None
isConnected = False
id = 0
if connect():
isConnected = True
client = Client()
print("Connection established")
time.sleep(1)
while isConnected:
rcvd = client.readServerMsg()
if (rcvd[:-1] == "yes"):
print_label(id)
elif (rcvd[0] == '@'):
id = rcvd[1:-1]
print(id, len(id))
id = int(id)
print(id, type(id))
data = read_csv(id)
if (type(id) == int):
sendCommand(data)
else:
print("Connection to %s:%d failed" % (IP_ADDRESS, IP_PORT))
print("done")