summaryrefslogtreecommitdiff
path: root/server.py
blob: a6e66c1fe479c99d4458afa0e29d9ddd2114f29b (plain) (blame)
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
#!/usr/bin/python3

import threading, time, json, ssl
#from simple_websocket_server import WebSocketServer, WebSocket
from websock import WebSocketServer, WebSocket
#from endpoint import MainEndpoint

###############################################################
# Configuration
f=open("pass.json", "r")
p=json.load(f)
f.close()

PORT=p["PORT"]
SECURE=p["SSL"]
clients = []

###############################################################
# Main Class
class WebSocketConn(WebSocket):
    def handle(self):
        global clients
        """
          Called when websocket frame is received.
          To access the frame data call self.data.
          i.e. The client sent us a message \o/

          If the frame is Text then self.data is a unicode object.
          If the frame is Binary then self.data is a bytearray object.
        """
        print("Message received from %s - %s" % (self.address[0], self.data))
        self.send_message('ACK')

    def connected(self):
        global clients
        """
          Called when a websocket client connects to the server.
        """
        print(self.address, 'connected')
        for client in clients:
            print(repr(client))
            client.send_message(self.address[0] + u' - connected')

        # TODO: Drop OLD connections when same ID tries to connect

        if (False):
            close(self, status=1000, reason='Unrecognized')
        else:
            clients.append(self)

    def handle_close(self):
        global clients
        """
          Called when a websocket server gets a Close frame from a client.
        """
        clients.remove(self)
        print(self.address, 'closed')
        for client in clients:
            client.send_message(self.address[0] + u' - disconnected')

    ##########################
    # Useful functions:
    # send_message()
    # send_fragment_start() / send_fragment() / send_fragment_end()
    #  
    ##########################


def MainWebsocket():
    if SECURE:
        server = WebSocketServer('', PORT, WebSocketConn,
                                 certfile="certificate.pem", keyfile="key.pem")
        print("Begin Secure Websocket at %d" % PORT)
    else:
        server = WebSocketServer('', PORT, WebSocketConn)
        print("Begin UNENCRYPTED Websocket at %d" % PORT)

    t = threading.Thread(target=server.serve_forever)
    t.daemon = True # Main server should not be a daemon?
    t.start()
    return
    #while True:
    #    time.sleep(86400)

# Broadcast function
def sendmsg(m, t="raw"):
    global clients
    # Format message according to type
    if t == "ping":
        msg="pong"
    else:
        msg=u"%s" % m

    # Send message
    for c in clients:
        c.send_message(msg)
    return

###############################################################
# Begin stuff
print("Starting...")
MainWebsocket()
print("Please wait...")
try:
    while True:
        time.sleep(15)
        sendmsg("Hello from SRV")
except:
    print("Terminating!")