0
\$\begingroup\$

Can HTTPS webserver host an HTML page that uses JS to connect with secured web socket protocol multiplayer game just like node js? If so point me in the correct direction to read more.

\$\endgroup\$
1
\$\begingroup\$

You can create a client websocket in browser-based JavaScript like this. Note the protocol wss:// before the URL of the server. wss is to ws like https is to http - it's websocket via TLS.

var socket = new WebSocket("wss://example.com/yourgameserver");
socket.onerror = errorHandler;
socket.onopen = openHandler;
socket.onmessage = messageHandler;

function errorHandler(error) {
     // your code to handle connection errors
}

function openHandler(event) {
     // your code to handle a successful connection. 
     // event.data might already contain the first data from the server
}

function messageHandler(event) {
     // your code to handle messages received from the server.
     // event.data will contain the message payload
}

After the connection is established, you can send data to the server with:

socket.send(data);

where data can be a String, ArrayBuffer, ArrayBufferView or Blob.

Check the documentation of the WebSocket API for further details.

But keep in mind that the websocket protocol won't allow you to connect to any multiplayer game. The WebSocket protocol isn't raw TCP/IP. The data is wrapped in a framing protocol. In order to allow a websocket connection, the server needs to understand that protocol.

Further, many websocket-based servers check the Origin header of incomming websocket requests to avoid connections from JS applications hosted on unauthorized websites. This header contains the URL of the website on which the script is running. So if you are trying to create an own client for a websocket server controlled by someone else, that server can easily refuse the connection.

\$\endgroup\$

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.