Advertisement
Guest User

Untitled

a guest
Jan 23rd, 2017
247
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Delphi 1.94 KB | None | 0 0
  1. type
  2.   TClient = class(TObject)
  3.     public
  4.       protocol : TWebSocketProtocol;
  5.       serverResponse : THttpServerResp;
  6.   end;
  7.  
  8.   TWebSocketProtocolEcho = class(TWebSocketProtocolChat)
  9.   protected
  10.     procedure EchoFrame(Sender: THttpServerResp; const Frame: TWebSocketFrame);
  11.   public
  12.     clients : TObjectList<TClient>;
  13.   end;
  14.  
  15. var
  16.   Server: TWebSocketServer;
  17.   protocol: TWebSocketProtocolEcho;
  18.  
  19.  
  20. procedure TWebSocketProtocolEcho.EchoFrame(Sender: THttpServerResp;
  21.   const Frame: TWebSocketFrame);
  22.   var
  23.     client : TClient;
  24. begin
  25.   TextColor(ccLightMagenta);
  26.   write(GetEnumName(TypeInfo(TWebSocketFrameOpCode),ord(Frame.opcode))^,' - ');
  27.   TextColor(ccWhite);
  28.   case Frame.opcode of
  29.     focContinuation:
  30.     begin
  31.       Self.clients.Add(tclient.Create);
  32.       Self.clients.Last.protocol := Self;
  33.       Self.clients.Last.serverResponse := Sender;
  34.       write('Connected');
  35.     end;
  36.     focConnectionClose:
  37.       write('Disconnected');
  38.     focText,focBinary:
  39.     begin
  40.       for client in self.clients do
  41.       begin
  42.         write('Echoing ',length(Frame.payload),' bytes');
  43.         SendFrame(client.serverResponse,Frame);
  44.       end;
  45.     end;
  46.   end;
  47.   TextColor(ccCyan);
  48.   writeln(' from ',Sender.ServerSock.RemoteIP,'/',PtrInt(Sender.ServerSock.Sock));
  49. end;
  50.  
  51. procedure Run;
  52. begin
  53.   Server := TWebSocketServer.Create('8888',nil,nil,'test');
  54.   try
  55.     protocol := TWebSocketProtocolEcho.Create('meow','');
  56.     protocol.clients := TObjectList<TClient>.Create(false);
  57.     protocol.OnIncomingFrame := protocol.EchoFrame;
  58.     Server.WebSocketProtocols.Add(protocol);
  59.     TextColor(ccLightGreen);
  60.     writeln('WebSockets Chat Server running on localhost:8888'#13#10);
  61.     TextColor(ccWhite);
  62.     writeln('Please load Project31SimpleEchoServer.html in your browser'#13#10);
  63.     TextColor(ccLightGray);
  64.     writeln('Press [Enter] to quit'#13#10);
  65.     TextColor(ccCyan);
  66.     readln;
  67.   finally
  68.     Server.Free;
  69.   end;
  70. end;
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement