Logo ROOT   6.30.04
Reference Guide
 All Namespaces Files Pages
ws.C
Go to the documentation of this file.
1 #include "THttpServer.h"
2 #include "THttpWSHandler.h"
3 #include "THttpCallArg.h"
4 #include "TString.h"
5 #include "TSystem.h"
6 #include "TDatime.h"
7 #include "TTimer.h"
8 
9 #include <cstdio>
10 
11 class TUserHandler : public THttpWSHandler {
12  public:
13  UInt_t fWSId;
14  Int_t fServCnt;
15 
16  TUserHandler(const char *name = 0, const char *title = 0) : THttpWSHandler(name, title), fWSId(0), fServCnt(0) {}
17 
18  // load custom HTML page when open correpondent address
19  TString GetDefaultPageContent() { return "file:ws.htm"; }
20 
21  virtual Bool_t ProcessWS(THttpCallArg *arg)
22  {
23  if (!arg || (arg->GetWSId()==0)) return kTRUE;
24 
25  // printf("Method %s\n", arg->GetMethod());
26 
27  if (arg->IsMethod("WS_CONNECT")) {
28  // accept only if connection not established
29  return fWSId == 0;
30  }
31 
32  if (arg->IsMethod("WS_READY")) {
33  fWSId = arg->GetWSId();
34  printf("Client connected %d\n", fWSId);
35  return kTRUE;
36  }
37 
38  if (arg->IsMethod("WS_CLOSE")) {
39  fWSId = 0;
40  printf("Client disconnected\n");
41  return kTRUE;
42  }
43 
44  if (arg->IsMethod("WS_DATA")) {
45  TString str;
46  str.Append((const char *)arg->GetPostData(), arg->GetPostDataLength());
47  printf("Client msg: %s\n", str.Data());
48  TDatime now;
49  SendCharStarWS(arg->GetWSId(), Form("Server replies:%s server counter:%d", now.AsString(), fServCnt++));
50  return kTRUE;
51  }
52 
53  return kFALSE;
54  }
55 
56  /// per timeout sends data portion to the client
57  virtual Bool_t HandleTimer(TTimer *)
58  {
59  TDatime now;
60  if (fWSId) SendCharStarWS(fWSId, Form("Server sends data:%s server counter:%d", now.AsString(), fServCnt++));
61  return kTRUE;
62  }
63 
64 };
65 
66 void ws()
67 {
68  THttpServer *serv = new THttpServer("http:8090");
69 
70  TUserHandler *handler = new TUserHandler("name1", "title1");
71 
72  serv->Register("/folder1", handler);
73 
74  const char *addr = "http://localhost:8090/folder1/name1/";
75 
76  printf("Starting browser with URL address %s\n", addr);
77  printf("In browser content of ws.htm file should be loaded\n");
78 
79  if (gSystem->InheritsFrom("TMacOSXSystem"))
80  gSystem->Exec(Form("open %s", addr));
81  else
82  gSystem->Exec(Form("xdg-open %s &", addr));
83 
84  // when connection will be established, data will be send to the client
85  TTimer *tm = new TTimer(handler, 3700);
86  tm->Start();
87 }