ECCE @ EIC Software
 All Classes Namespaces Files Functions Variables Typedefs Enumerations Enumerator Friends Macros Groups Pages
remote_msg_buffer.cc
Go to the documentation of this file. Or view the newest version in sPHENIX GitHub for file remote_msg_buffer.cc
1 
2 #include "remote_msg_buffer.h"
3 
4 // in the constructor we allocate the specified amount of bytes for
5 // the output array.
6 
7 remote_msg_buffer::remote_msg_buffer(const char *host, const int port, const int msglen)
8  : msg_buffer(msglen)
9 {
10  // in the constructor we replace COUT's streambuf with this one.
11  // we remember the old one because we may want to replace it.
12 
13 #ifdef RDBUF_ACCEPTS_STREAMBUF
14  original_streambuf = COUT.rdbuf ( (STREAMBUF *) this);
15 #else
16  original_streambuf = COUT.rdbuf ();
17  COUT = (STREAMBUF *) this;
18 #endif
19 
20  ThePort = port;
21  TheHost = new char [ strlen(host) +1 ];
22  strcpy (TheHost, host);
23 
24  p_host = gethostbyname(TheHost);
25  COUT << p_host->h_name << ENDL;
26 
27  memset ( (void*) &server_addr, 0, sizeof(server_addr) );
28  server_addr.sin_family = AF_INET;
29 
30  //bcopy(p_host->h_addr, &(server_addr.sin_addr.s_addr), p_host->h_length);
31  memcpy (&(server_addr.sin_addr.s_addr), p_host->h_addr, p_host->h_length);
32 
33  server_addr.sin_port = htons(ThePort);
34 
35 }
36 
37 // in the destructor, we restore the original streambuf for COUT.
39 {
40 #ifdef RDBUF_ACCEPTS_STREAMBUF
41  COUT.rdbuf ( original_streambuf);
42 #else
44 #endif
45  delete [] TheHost;
46 
47 }
48 
49 // this is the function which is called as a result of the << std::endl
50 // and flush() operations
51 #if defined(LVL2_WINNT) || defined(STREAMBUF_NEW_IOSTREAM)
52 int remote_msg_buffer::pubsync ()
53 #else
55 #endif
56 {
57 
58  msgProfile mp;
59  int length, ix;
60 
61 
62  char *x = format(&length, &mp);
63  int ret = 0;
64 
65 #if defined(LVL2_WINNT) || defined(STREAMBUF_NEW_IOSTREAM)
66  for (ix =0; ix < length; ix++)
67  {
68  original_streambuf->sputc( x[ix] );
69  }
70  ret = original_streambuf->pubsync();
71 #else
72  for (ix =0; ix < length; ix++)
73  {
74  original_streambuf->overflow( x[ix] );
75  }
76  ret = original_streambuf->sync();
77 #endif
78 
79  send_string(x, length);
80 
81  delete [] x;
82 
83  pos = 0;
84 
85  return ret;
86 }
87 
88 void remote_msg_buffer::send_string(const char *x, const int len)
89 {
90 
91 
92  if ( (sockfd = socket(AF_INET, SOCK_STREAM, 0) ) < 0 )
93  {
94  return;
95  }
96 
97  if ( connect(sockfd, (struct sockaddr*) &server_addr
98  , sizeof(server_addr)) < 0 )
99  {
100  return;
101  }
102  writen (sockfd, x, len);
103 
104  close (sockfd);
105 }
106 
107 int remote_msg_buffer::writen (int fd, const char *ptr, int nbytes)
108 {
109  int nleft, nwritten;
110  nleft = nbytes;
111  while ( nleft>0 )
112  {
113  nwritten = write (fd, ptr, nleft);
114  if ( nwritten < 0 )
115  return nwritten;
116 
117  nleft -= nwritten;
118  ptr += nwritten;
119  }
120  return (nbytes-nleft);
121 }