procedure TSocketHandler.MessageReceived(Sender: TObject);
var
Messages: TWebsocketMessageOwnerList;
m: TWebsocketMessage;
Comm: TWebsocketCommunicator;
jo: TJSONObject;
func, utype, uname, pwd, token: string;
msg, val, res: string;
conn: TWSConnection;
cp: PWSConnection;
begin
Comm := TWebsocketCommunicator(Sender);
Messages := TWebsocketMessageOwnerList.Create(True);
jo := TJSONObject.Create;
try
Comm.GetUnprocessedMessages(Messages);
for m in Messages do begin
if m is TWebsocketStringMessage then begin
msg := TWebsocketStringMessage(m).Data;
WriteLn('Message from ', Comm.SocketStream.RemoteAddress.Address,
':', Comm.SocketStream.RemoteAddress.Port, ' - ', msg);
jo := GetJSON(msg) as TJSONObject;
func := jo.Get('msgtype');
if func = 'gettoken' then begin
utype := jo.Get('usertype');
uname := jo.Get('uname');
pwd := jo.Get('upassword');
token := GenToken(utype, uname, pwd);
ConfirmConn(uname, token, comm);
jo.Clear;
jo.Add('msgtype', 'tokenreturn');
jo.Add('token', token);
res := jo.AsJSON;
Comm.WriteStringMessage(res);
end else begin
if not GetConnByCommunicator(comm, conn) then continue;
if conn.utype <> 'monitor' then begin
GetConnsByType('monitor', monitorList);
for cp in monitorList do begin
if cp^.token = '' then continue;
cp^.writeMsg.Add(msg);
end;
end else begin
if func = 'subscribe' then begin
val := jo.Get('boxname');
if val = null then continue;
if not GetConnByUname(val, conn) then continue;
jo.Clear;
jo.Add('msgtype', 'subscribe');
jo.Add('switch', 'on');
res := jo.AsJSON;
conn.writeMsg.Add(res);
jo.Clear;
jo.Add('msgtype', 'forcereport');
res := jo.AsJSON;
conn.writeMsg.Add(res);
end else if func = 'unsubscribe' then begin
val := jo.Get('boxname');
if val = null then continue;
if not GetConnByUname(val, conn) then continue;
jo.Clear;
jo.Add('msgtype', 'subscribe');
jo.Add('switch', 'off');
res := jo.AsJSON;
conn.writeMsg.Add(res);
end;
end;
end;
end else begin
msg := TWebsocketStringMessage(m).Data;
//i don't know how to handle messages like ping pong close.... just leave it here
end;
end;
finally
Messages.Free;
jo.Free;
end;
end;