socket javascript code example

Example 1: javascript websocket example code

var Socket = new WebSocket('ws://' + window.location.hostname + ':81/'); // The '81' here is the Port where the WebSocket server will communicate with
// The instance of the WebSocket() class (i.e. Socket here), must need to be globally defined

Socket.send("pass your data here, and it'll be String"); // This method one can call locally

Example 2: socket io script

<script src="/socket.io/socket.io.js"></script>
<script>
  const socket = io();
</script>

Example 3: js connect to websocket

var exampleSocket = new WebSocket("wss://www.example.com/socketserver", "protocolOne");

Example 4: socket io

npm install --save socket.io