-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathsocket_server.py
More file actions
72 lines (56 loc) · 1.73 KB
/
socket_server.py
File metadata and controls
72 lines (56 loc) · 1.73 KB
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
#!/usr/bin/python
import socket
import sys
from check_pkg import *
from thread import *
HOST = '' # Symbolic name, meaning all available interfaces
PORT = 10000 # Arbitrary non-privileged port
DIST = 'Jessie' # Distribution name
try:
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
logging.info('Socket created')
except socket.error:
logging.info('Socket error')
repos = Repository()
logging.info('Initialized Repository...')
# Bind socket to local host and port
try:
s.bind((HOST, PORT))
except socket.error as msg:
logging.info('Bind failed. Error Code : ' + str(msg[0]) + ' Message ' + msg[1])
sys.exit()
logging.info('Socket bind complete')
# Start listening on socket
s.listen(10)
logging.info('Socket now listening')
# Function for handling connections. This will be used to create threads
def clientthread(conn):
logging.info('starting clientthread...')
while True:
try:
# Receiving from client
data = conn.recv(1024)
if data:
logging.info('received data: {}'.format(data))
if data == "#START#":
reply = repos.get_packages(DIST)
conn.sendall(reply + "#END#")
else:
pass
except Exception as e:
logging.info('clientthread Error: {}'.format(e))
break
conn.close()
if __name__ == '__main__':
# now keep talking with the client
while 1:
try:
# wait to accept a connection - blocking call
conn, addr = s.accept()
logging.info('Connected with ' + addr[0] + ':' + str(addr[1]))
# start new thread takes 1st argument as a function name to be run, second is the tuple of arguments to the function.
start_new_thread(clientthread, (conn,))
except Exception as e:
logging.info('main Error: {}'.format(e))
s.close()