This script is used to establish a server client connexion between two terminals (two computers)
Connection
A class to establish connection between two terminals through sockets
Source code in pyDecNef/2_client/1_training/server_client_connexion.py
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
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122 | class Connection:
""" A class to establish connection between two terminals through sockets"""
def __init__(self):
self.ip = IP #Set the IP address for connection.
self.port = PORT #Set the port number for connection.
self.format = FORMAT #Set the data format (e.g., 'utf-8').
self.n_bytes = N_BYTES #Set the maximum number of bytes to receive.
socket.setdefaulttimeout(TIMEOUT) # Set a timeout (when client/server do not send/receive any
# data for this timeframe, then close connection)
def start_server(self):
""" A class method to initialize server connection side """
self.server = socket.socket(socket.AF_INET, # Start TCP/IP socket
socket.SOCK_STREAM)
self.server.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1) # To be able to create again a new server on this
# IP and PORT after closing actual server terminal
self.type = 'server' # Connection type
try: # Try to bind server to IP and PORT
print(Fore.YELLOW + '[STARTING] Server is starting...')
self.server.bind((self.IP, # Set IP address to be the server address
self.PORT)) # Set a port to connect with clients (usually above 1000))
except socket.error:
print(Fore.RED + f'[ERROR] Server connection to {self.IP} on port {self.PORT} has failed.')
print(Fore.YELLOW + '[CLOSING] Closing server...')
sys.exit() # To close server script in case connection to specified IP and PORT fails
self.server.listen() # Listen for new connections
print(Fore.YELLOW + f'[WAITING] Waiting for connection with the experimental software on {self.IP} and port {self.PORT}')
while True: # Loop awaiting for a connection
self.client, self.client_address = self.server.accept() # When connection to a client occurs assigns client data
# to client_address (IP:PORT) and stablish a client_socket
if self.client:
break
print(Fore.GREEN + f'[CONNECTED] Connection with {self.client_address} has been established.')
def start_client(self):
"""A class method to initialize client connection side """
self.client = socket.socket(socket.AF_INET, # Start TCP/IP socket
socket.SOCK_STREAM)
self.type = 'client' # Connection type
try:
print(Fore.YELLOW + '[STARTING] Client is starting...')
self.client.connect((self.IP, # To connect to the server side
self.PORT)) # Set a port to connect to (usually above 1000))
print(Fore.GREEN + f'[CONNECTED] You are now connected to {self.IP} on port {self.PORT}.')
except socket.error:
print(Fore.RED + f'[ERROR] Connection to server {self.IP} on port {self.PORT} has failed.')
print(Fore.YELLOW + '[CLOSING] Closing client...')
sys.exit() # To close the client script in case connection to specified IP and PORT fails
def listen(self):
"""A class method to listen for incoming packets"""
print(Fore.YELLOW + '[WAITING] Waiting for messages...')
data = []
signal.signal(signal.SIGALRM, timeout)
signal.alarm(1) ### 1 seconds time out for the data segment (intersegments timeout time)
while True:
try:
packet = self.client.recv(self.N_BYTES) # Receive the message
except TimeoutError:
print("finished listening..")
break
if not packet:
print("end of packet segments")
data.append(packet)
print("finished receiving all data segments.")
message = pickle.loads(b"".join(data)) # Unpickle the message
print(Fore.GREEN + f'[RECEIVED] Message: "{message}" received.')
return message
def send(self, message):
"""A class method to send packets"""
print(Fore.YELLOW + f'[SENDING] Sending "{message}"...')
message = pickle.dumps(message) # Pickle the message
self.client.send(message) # Send message
|
listen()
A class method to listen for incoming packets
Source code in pyDecNef/2_client/1_training/server_client_connexion.py
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114 | def listen(self):
"""A class method to listen for incoming packets"""
print(Fore.YELLOW + '[WAITING] Waiting for messages...')
data = []
signal.signal(signal.SIGALRM, timeout)
signal.alarm(1) ### 1 seconds time out for the data segment (intersegments timeout time)
while True:
try:
packet = self.client.recv(self.N_BYTES) # Receive the message
except TimeoutError:
print("finished listening..")
break
if not packet:
print("end of packet segments")
data.append(packet)
print("finished receiving all data segments.")
message = pickle.loads(b"".join(data)) # Unpickle the message
print(Fore.GREEN + f'[RECEIVED] Message: "{message}" received.')
return message
|
send(message)
A class method to send packets
Source code in pyDecNef/2_client/1_training/server_client_connexion.py
116
117
118
119
120
121
122 | def send(self, message):
"""A class method to send packets"""
print(Fore.YELLOW + f'[SENDING] Sending "{message}"...')
message = pickle.dumps(message) # Pickle the message
self.client.send(message) # Send message
|
start_client()
A class method to initialize client connection side
Source code in pyDecNef/2_client/1_training/server_client_connexion.py
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92 | def start_client(self):
"""A class method to initialize client connection side """
self.client = socket.socket(socket.AF_INET, # Start TCP/IP socket
socket.SOCK_STREAM)
self.type = 'client' # Connection type
try:
print(Fore.YELLOW + '[STARTING] Client is starting...')
self.client.connect((self.IP, # To connect to the server side
self.PORT)) # Set a port to connect to (usually above 1000))
print(Fore.GREEN + f'[CONNECTED] You are now connected to {self.IP} on port {self.PORT}.')
except socket.error:
print(Fore.RED + f'[ERROR] Connection to server {self.IP} on port {self.PORT} has failed.')
print(Fore.YELLOW + '[CLOSING] Closing client...')
sys.exit() # To close the client script in case connection to specified IP and PORT fails
|
start_server()
A class method to initialize server connection side
Source code in pyDecNef/2_client/1_training/server_client_connexion.py
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 | def start_server(self):
""" A class method to initialize server connection side """
self.server = socket.socket(socket.AF_INET, # Start TCP/IP socket
socket.SOCK_STREAM)
self.server.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1) # To be able to create again a new server on this
# IP and PORT after closing actual server terminal
self.type = 'server' # Connection type
try: # Try to bind server to IP and PORT
print(Fore.YELLOW + '[STARTING] Server is starting...')
self.server.bind((self.IP, # Set IP address to be the server address
self.PORT)) # Set a port to connect with clients (usually above 1000))
except socket.error:
print(Fore.RED + f'[ERROR] Server connection to {self.IP} on port {self.PORT} has failed.')
print(Fore.YELLOW + '[CLOSING] Closing server...')
sys.exit() # To close server script in case connection to specified IP and PORT fails
self.server.listen() # Listen for new connections
print(Fore.YELLOW + f'[WAITING] Waiting for connection with the experimental software on {self.IP} and port {self.PORT}')
while True: # Loop awaiting for a connection
self.client, self.client_address = self.server.accept() # When connection to a client occurs assigns client data
# to client_address (IP:PORT) and stablish a client_socket
if self.client:
break
print(Fore.GREEN + f'[CONNECTED] Connection with {self.client_address} has been established.')
|