title: Creating a "Hello World" WebSocket example
body: <p>I don't understand why I cannot make the following code work. I want to connect with JavaScript to my server console application. And then send data to the server.</p>
  
  <p>Here is the server code:</p>
  
  <pre><code>    static void Main(string[] args)
      {            
          TcpListener server = new TcpListener(IPAddress.Parse("127.0.0.1"), 9998);
          server.Start();
          var client = server.AcceptTcpClient();
          var stream = client.GetStream();
  
          while (true)
          {
              var buffer = new byte[1024]; 
              // wait for data to be received
              var bytesRead = stream.Read(buffer, 0, buffer.Length);                
              var r = System.Text.Encoding.UTF8.GetString(buffer);
              // write received data to the console
              Console.WriteLine(r.Substring(0, bytesRead));
          }
      }
  </code></pre>
  
  <p>and here is the JavaScript:</p>
  
  <pre><code>        var ws = new WebSocket("ws://localhost:9998/service");
          ws.onopen = function () {
              ws.send("Hello World"); // I WANT TO SEND THIS MESSAGE TO THE SERVER!!!!!!!!
          };
  
          ws.onmessage = function (evt) {
              var received_msg = evt.data;
              alert("Message is received...");
          };
          ws.onclose = function () {
              // websocket is closed.
              alert("Connection is closed...");
          };
  </code></pre>
  
  <p>When I run that code this is what happens:</p>
  
  <p><a href="https://i.stack.imgur.com/pgnSt.png" rel="noreferrer"><img src="https://i.stack.imgur.com/pgnSt.png" alt=""></a></p>
  
  <p>Note that when I run the JavaScript the server accepts and successfully establishes a connection. JavaScript is not able to send data though. Whenever I place the send method it will not send even though a connection is established. How can I make this work?</p>