-
Notifications
You must be signed in to change notification settings - Fork 0
/
Server.py
188 lines (150 loc) · 7 KB
/
Server.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
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
#!/usr/bin/python
# -*- coding: utf-8 -*-
#------------------------------------------------------------------------------#
# Client / Server Architecture #
# ============================================================================ #
# Developer: Chavaillaz Johan #
# Filename: Server.py #
# Version: 1.0 #
# #
# Licensed to the Apache Software Foundation (ASF) under one #
# or more contributor license agreements. See the NOTICE file #
# distributed with this work for additional information #
# regarding copyright ownership. The ASF licenses this file #
# to you under the Apache License, Version 2.0 (the #
# "License"); you may not use this file except in compliance #
# with the License. You may obtain a copy of the License at #
# #
# http://www.apache.org/licenses/LICENSE-2.0 #
# #
# Unless required by applicable law or agreed to in writing, #
# software distributed under the License is distributed on an #
# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY #
# KIND, either express or implied. See the License for the #
# specific language governing permissions and limitations #
# under the License. #
# #
#------------------------------------------------------------------------------#
#------------------------------------------------------------------------------#
# #
# LIBRARIES IMPORT #
# #
#------------------------------------------------------------------------------#
import socket
import sys
import threading
import argparse
import re
from collections import OrderedDict
#------------------------------------------------------------------------------#
# #
# UTILITIES FUNCTIONS #
# #
#------------------------------------------------------------------------------#
def prepareString(content):
return bytes(content + "\n", 'UTF-8')
def getArguments(message):
return message.split(" ")[1:]
#------------------------------------------------------------------------------#
# #
# RESPONSE FUNCTIONS #
# #
#------------------------------------------------------------------------------#
def helloRequest(thread):
thread.send("MSG Hello from " + socket.gethostname())
def closeConnectionRequest(thread):
thread.closeConnection = True
thread.send("CLOSE CONFIRM")
def notFoundRequest(thread):
thread.send("MSG Command not found")
#------------------------------------------------------------------------------#
# #
# CLASSES #
# #
#------------------------------------------------------------------------------#
class ThreadClient(threading.Thread):
"""Manage each client connection to the server in a new thread"""
functionArray = OrderedDict([
(r"HELLO", helloRequest),
(r"CLOSE", closeConnectionRequest),
(r".*", notFoundRequest),
])
def __init__(self, connection):
threading.Thread.__init__(self)
self.connection = connection
self.closeConnection = False
self.data = {}
self.data['message'] = ""
print("%s connected" % self.getName())
def send(self, message):
print("%s -> %s" % (self.getName(), message))
self.connection.send(prepareString(message))
def run(self):
try:
while not self.closeConnection:
character = self.connection.recv(1)
if character == b'\n':
print("%s <- %s" % (self.getName(), self.data['message']))
for regex, function in ThreadClient.functionArray.items():
if re.match(regex, self.data['message']):
function(self)
break
self.data['message'] = ""
else:
self.data['message'] += character.decode('UTF-8')
except ConnectionResetError:
print("%s has reset connection" % self.getName())
# Close connection
self.connection.close()
del connectionList[self.getName()]
print("%s disconnected" % self.getName())
#------------------------------------------------------------------------------#
# #
# "MAIN" FUNCTION #
# #
#------------------------------------------------------------------------------#
# If this is the main module, run this
if __name__ == '__main__':
argsCount = len(sys.argv)
# Create argument parser to help user
parser = argparse.ArgumentParser(
description='Server instance for client-server communication.'
)
parser.add_argument(
'port',
nargs='+',
type=str,
help='Port to use to receive connections (Default: 1991).'
)
# Show help if one of the arguments is missing
if argsCount not in [1, 2]:
parser.print_help()
sys.exit()
# Get configuration
host = '127.0.0.1'
port = int(sys.argv[1]) if argsCount == 3 else 1991
# Server initialization
serverSocket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
try:
serverSocket.bind((host, port))
except socket.error:
print("Socket creation failed, maybe the port is already in use ?")
sys.exit()
# Listen new connection
print("Server ready, waiting for requests ...")
serverSocket.listen(1)
# Connection list (clients)
connectionList = {}
try:
while True:
connection, adresse = serverSocket.accept()
# Start a new client
thread = ThreadClient(connection)
thread.start()
# Store connection
id = thread.getName()
connectionList[id] = connection
# Send a welcome message
thread.send("MSG Welcome aboard !")
except KeyboardInterrupt:
print("Server shut down")