Paul Kiarie
Paul Kiarie

Reputation: 37

How to set the WebSocket subprotocol in js

Am creating a client websocket with javascript andam lost where to put this key "Sec-WebSocket-Key : dGhlIHNhbXBsZSBub25jZQ==" Trying to do with the code below but I get the error

index.html:14 Uncaught DOMException: Failed to construct 'WebSocket': The subprotocol 'dGhlIHNhbXBsZSBub25jZQ==' is invalid. at WebSocketTest (file:///C:/handshake/index.html:14:16) at :1:1

<script type = "text/javascript">
         function WebSocketTest() {
            
            if ("WebSocket" in window) {
               alert("WebSocket is supported by your Browser!");
               
               // Let us open a web socket
               //var ws = new WebSocket("ws://192.168.1.104:9001");
			   var ws = new WebSocket("wss://192.168.1.104:9001", "dGhlIHNhbXBsZSBub25jZQ==");
                ws.onopen = function() {
                  //test open connectin
				  alert("Connection Established...");
                  // Web Socket is connected, send data using send()
                  ws.send("Message to send");
                  alert("Message is sent...");
               };
				
               ws.onmessage = function (evt) { 
                  var received_msg = evt.data;
                  alert("Message is received...");
               };
				
               ws.onclose = function() { 
                  
                  // websocket is closed.
                  alert("Connection is closed..."); 
               };
            } else {
              
               // The browser doesn't support WebSocket
               alert("WebSocket NOT supported by your Browser!");
            }
         }
      </script>
  <body>
      <div id = "sse">
         <a href = "javascript:WebSocketTest()">Run WebSocket</a>
		 <p> Tested </p>
      </div>
      
   </body>

   </body>

Upvotes: 1

Views: 5411

Answers (1)

ottomeister
ottomeister

Reputation: 5828

It's kinda strange that the title of this question talks about setting a WebSocket subprotocol but the text of the question and the code excerpt are concerned with the WebSocket security key. Those are two completely different things.

The JavaScript WebSocket object provides no access to the Sec-WebSocket-Key header. That header is generated internally by the browser's WebSocket implementation. From JavaScript you can't set that key and you can't read that key.

The second argument to the WebSocket constructor lets you specify content (one or more subprotocol names) for the Sec-WebSocket-Protocol header, not for Sec-WebSocket-Key. That's why the error message complains about being given an invalid subprotocol name when you pass "dGhlIHNhbXBsZSBub25jZQ==" as that argument.

Upvotes: 1

Related Questions