title: making the Websocket using the c++ server
body: <p>I was making the server in c++ to connect to WebSocket but somehow, it was not connecting with the websocket. The WebSocket is showing the connection is closed and there is also some problem in the c++ server, as on second call to the server from WebSocket, it is showing the following error - double free or corruption (out). I have spend a lot of time on it. Here is the code:
  c++ </p>
  
  <pre><code>#include&lt;iostream&gt;
  #include &lt;string&gt;
  #include &lt;stdio.h&gt;
  #include &lt;unistd.h&gt;
  #include &lt;stdlib.h&gt;
  #include &lt;errno.h&gt;
  #include &lt;string.h&gt;
  #include &lt;time.h&gt;
  #include &lt;sys/types.h&gt;
  #include &lt;sys/socket.h&gt;
  #include &lt;netinet/in.h&gt;
  #include &lt;arpa/inet.h&gt;
  #include &lt;netdb.h&gt;
  
  
  using namespace std;
  
  string getConnectionKey(char*);
  void acceptConnection(int, const char*);
  void readConnection(int);
  void bail(char*);
  string executeShellCommand(const string&amp;);
  string getBase64Encoded(string);
  char *getClientKey(char*);
  string getSHA1Hash(string);
  
  int main()
  {
    char srvr_adr[]  = "127.0.0.1";
    char srvr_port[] = "9099";
  
    struct sockaddr_in adr_srvr;
    struct sockaddr_in adr_clnt;
  
    socklen_t len_inet;
    int s;       // Server Socket
    int c;      // Client Socket
    int z;
    char *data;
    char readdata[256];
  
    int count = 2;
  
    data  = (char*)malloc(sizeof(char)*128);
  
    s = socket(PF_INET, SOCK_STREAM, 0);
  
    if(s  ==  -1)
      bail("socket()");
  
    memset(&amp;adr_srvr,0,sizeof(adr_srvr));
    adr_srvr.sin_family = AF_INET;
    adr_srvr.sin_port = htons(atoi(srvr_port));
  
    if( strcmp(srvr_adr,"*")!=0)
    {
      adr_srvr.sin_addr.s_addr  = inet_addr(srvr_adr);
      if(adr_srvr.sin_addr.s_addr ==  INADDR_NONE)
        bail(" INVALID ADRESS \n");
    }
    else /* WILD ADDRESS*/
      adr_srvr.sin_addr.s_addr  = INADDR_ANY;
  
    len_inet  = sizeof adr_srvr;
    z = bind(s,(struct sockaddr*)&amp;adr_srvr, len_inet);
  
    if(z==-1)
      bail("bind(2)");
  
    z = listen(s,10);
  
    if(z==-1)
      bail("listen(2)");
  
    for(;;)
    {
      len_inet  = sizeof(adr_clnt);
      c = accept(s, (struct sockaddr*)&amp;adr_clnt,&amp;len_inet);
  
      if(c==-1)
        bail("accept(2)");
  
      readConnection(c);
  
      close(c);
    }
    return 0; 
  }
  
  void readConnection(int c)
  {
      int z;
      char readdata[256];
  
      // READING
      z = read(c,readdata, sizeof(readdata)-1);
      if(z==-1)
        bail("read(2)");
      else if(strlen(readdata)&gt;0)
        printf(" READ \n%s\n", readdata);
  
      string key =  getConnectionKey(readdata);
      cout&lt;&lt;" KEY "&lt;&lt;key&lt;&lt;endl;
      acceptConnection(c, key.c_str());
  }
  
  void acceptConnection(int c, const char *key)
  {
      int z;      
      char response[]  = "HTTP/1.1 101 Switching Protocols\nUpgrade: websocket\nConnection: Upgrade\nSec-WebSocket-Accept: ";
      char *output;
      output  = (char*)malloc( sizeof(char) * ( strlen(key) + strlen(response) + 1) );
      strcat(output, response);
      strcat(output, key);
  
      cout&lt;&lt;" output "&lt;&lt;output&lt;&lt;endl;
      // WRITING
      z = write(c, output, strlen(output));
      if(z  ==  -1)
        bail("write(2)");
  
      printf(" Connection Done \n"); 
  }
  
  string getConnectionKey(char *str)
  {
    char *start,*end,*key;
    int len;
    string s("258EAFA5-E914-47DA-95CA-C5AB0DC85B11");
  
    // GET CLIENT KEY
    key = getClientKey(str);
  
    // Appending the key
    s = key + s;
  
    // SHA1 HASH
    string out  = getSHA1Hash(s);
    //hashwrapper *h  = new sha1wrapper();
    //string out  = h-&gt;getHashFromString(s);
  
    // BASE 64 ENCODING
    string encoded = getBase64Encoded(out);
    //encoded = (char*)malloc(sizeof(char)*256);
    //strcpy(encoded, getBase64Encoded(out) );
  
    free(key);
    //delete h;
    return encoded;
  }
  char *getClientKey(char *str)
  {
    int len;
    char *start,*end,*key;
  
    start  = strstr(str,  "Sec-WebSocket-Key:");
    if(start ==  NULL)
      return false;
    start +=  17;
  
    end = strstr(start, "==");
    if(end  ==  NULL)
      return false;
  
    end++;
  
    while( !(*start&gt;=65 &amp;&amp; *start&lt;=90 || *start &gt;= 97 &amp;&amp;  *start&lt;=122 || *start&gt;=48 &amp;&amp; *start&lt;=57 || *start == '+' || *start=='/') )
      start++;
    len = end - start + 1;
    key = (char*) malloc( sizeof(char) * (len+1) );
    strncpy(key,start,len);
  
    return key;
  }
  
  string getBase64Encoded(string s)
  {
    int len;
    string str="";
    len = s.length();
    char *command;
  
    for(int i=len-1 ; i&gt;=1; i=i-2)
    {
      str = s.substr(i-1,2) + str;
      str = "\\x" + str;
    }
    if(len%2==1)
    {
      str = s[0]  + str;
      str = "\\x" + str;
    }
    // making the command to be send to shell
    str = "printf \"" + str ;
    str = str + "\" | base64";
  
    cout&lt;&lt;endl&lt;&lt;" STRING "&lt;&lt;str&lt;&lt;endl;
    return executeShellCommand(str);
  }
  string getSHA1Hash(string str)
  {
    int len ;
    string output;
    str = "printf \""+str;
    str = str +"\" | sha1sum";
    cout&lt;&lt;str&lt;&lt;endl;
    output  = executeShellCommand(str);
  
    return output.substr(0,output.length()-4);;
  }
  string executeShellCommand(const string&amp; cmd)
  {
     FILE *fpipe;
  
     if ( !(fpipe = (FILE*)popen(cmd.c_str(),"r")) )
     {  // If fpipe is NULL
       perror("Problems with pipe");
       exit(1);
     }
  
     char buf[256] = "";
     string line="";
     while ( fgets( buf, sizeof buf, fpipe)  )
     {
       if(strlen(buf)&gt;0)
          line.append(buf);
       memset(buf, 0, sizeof(buf));
  
     }
     // CLOSE THE PIPE
      pclose(fpipe);
  
     return line;
  }
  void bail(char *on_what)
  {
    if(errno!=0)
    {
      fputs( strerror(errno), stderr);
      fputs( ":", stderr);
    }
    fputs( on_what, stderr);
    fputs("\n",stderr);
  }
  </code></pre>
  
  <p>Here is the Websocket Code:</p>
  
  <pre><code>&lt;!doctype html&gt;
  &lt;html&gt;
  &lt;head&gt;
  &lt;meta charset="UTF-8"&gt;
  &lt;title&gt;WebSocket Chat&lt;/title&gt;
  &lt;/head&gt;
  &lt;body&gt;
  &lt;h1&gt;WebSocket Chat&lt;/h1&gt;
  &lt;section id="content"&gt;&lt;/section&gt;
  &lt;input id="message" type="text" tabindex="1"/&gt;
  &lt;textarea id="show"&gt;
  &lt;/textarea&gt;
  &lt;script src="http://www.google.com/jsapi"&gt;&lt;/script&gt;
  &lt;script&gt;google.load("jquery", "1.3")&lt;/script&gt;
  &lt;script src="http://jquery-json.googlecode.com/files/jquery.json-2.2.min.js"&gt;&lt;/script&gt;
  &lt;!--script src="http://jquery-websocket.googlecode.com/files/jquery.websocket-0.0.1.js"&gt;&lt;/script--&gt;
  &lt;script src="/js/jquery.websocket-0.0.1.js"&gt;&lt;/script&gt;
  &lt;script type="text/javascript"&gt;
  
  /*var ws =  $.websocket("ws://127.0.0.1:9099/", 
            {
              events: {
                              message: function(e) 
                              {
                                alert("e.data");
                                $('#content').append(e.data + '&lt;br&gt;') 
                              }
                      }
            });*/
  var websocketConnection = new WebSocket("ws://127.0.0.1:9099/");
  websocketConnection.onopen = function(ev)
  {
          showmsg('Connected to the echo service');
  };
  websocketConnection.onerror = function(ev)
  {
    showmsg(" ERROR : ".ev.data);
  }
  websocketConnection.onclose = function(ev)
  {
    showmsg(" Connection Closed");
  };
  websocketConnection.onmessage = function(event) 
  {
        showmsg(event.data);
        $('#content').append(event.data+"&lt;br&gt;");
  };
  showmsg(" CURRENT STATE "+websocketConnection.readyState);
  if(!websocketConnection)
    showmsg(" object null ");
  websocketConnection.send("Hello Echo Server");
  
  $('#message').change(function(){
        flag  = ws.send('message', this.value);
        if(!flag)
          alert("not send");
  
          this.value = '';
          });
  function showmsg(content)
  {
    $('#show').val(content+"&lt;br&gt;");
  }
  &lt;/script&gt;
  &lt;/body&gt;
  &lt;/html&gt;
  </code></pre>
  
  <p>Please Help me out , what is the problem in the C++ and what is the response to be sent to the WebScoket. </p>