-
Notifications
You must be signed in to change notification settings - Fork 15
/
Copy pathNetworkTcpServer.py
68 lines (56 loc) · 1.74 KB
/
NetworkTcpServer.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
"""
Network features
"""
import socket
import time
class PyNetwork(object):
def __init__(self, ip, port, delay):
self.ip = ip
self.port = port
self.delay = delay # milliseconds
def send_data(self, data=None, delay=None):
if data is None:
return 42
self.delay = delay
tries = 8
# Create socket
try:
sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
except Exception as exc:
print("Exception create socket: " + str(exc))
return False
# Set socket options
try:
sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
except socket.error as exc:
sock.close()
print("Failed set socket options: " + str(exc))
print("Failed 'send_data'!")
return False
# Connect
sock.settimeout(float(self.delay) / 1000)
start = int(round(time.time() * 1000))
while True:
try:
sock.connect((self.ip, self.port))
break
except Exception as exc:
if int(round(time.time() * 1000)) - start >= self.delay:
print("Exception connect socket: %s" % str(exc))
return False
sock.settimeout(None)
# Read data from file and send
try:
sock.send(data)
except Exception as exc:
print("Exception send packet: " + str(exc))
return False
# Close socket
try:
sock.close()
except socket.error as exc:
print("Exception close socket: " + str(exc))
return False
return True
def initialization():
return PyNetwork