forked from zgemma-star/e2plugins
-
Notifications
You must be signed in to change notification settings - Fork 5
/
datasocket.py
75 lines (66 loc) · 1.86 KB
/
datasocket.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
# -*- coding: utf-8 -*-
import struct
import os
from twisted.internet.protocol import ServerFactory, Protocol
browserclients = []
onCommandReceived = []
onBrowserClosed = []
class ClientConnection(Protocol):
magic = 987654321
data = ''
headerformat = '!III'
headersize = struct.calcsize(headerformat)
datasize = 0
cmd = 0
def dataReceived(self, data):
self.data += data
while len(self.data):
if self.datasize == 0:
if len(self.data) >= self.headersize:
(magic, self.cmd, self.datasize) = struct.unpack(self.headerformat, self.data[:self.headersize])
self.data = self.data[self.headersize:]
if magic != self.magic:
self.data = ''
self.datasize = 0
if len(self.data) >= self.datasize:
global onCommandReceived
for x in onCommandReceived:
x(self.cmd, self.data[:self.datasize])
break
self.data = self.data[self.datasize:]
self.datasize = 0
else:
break
def connectionMade(self):
global browserclients
browserclients.append(self)
def connectionLost(self, reason):
global browserclients
browserclients.remove(self)
if not len(browserclients):
global onBrowserClosed
for x in onBrowserClosed:
x()
class CommandServer:
def __init__(self):
from twisted.internet import reactor
self.factory = ServerFactory()
self.factory.protocol = ClientConnection
try:
os.remove('/tmp/.sock.stalker')
except:
pass
self.port = reactor.listenUNIX('/tmp/.sock.stalker', self.factory)
def __del__(self):
global browserclients
for client in browserclients:
client.transport.loseConnection()
def sendCommand(self, cmd, data = ''):
global browserclients
for client in browserclients:
client.transport.write(struct.pack('!III', client.magic, cmd, len(data)))
if len(data):
client.transport.write(data)
def connectedClients(self):
global browserclients
return len(browserclients)