title: My WebSocket is not working as expected; the server is implemented in Java and the Client is in JavaScript
body: <p>I seem to be having trouble getting a 'proper' connection between my Java server and my JavaScript client. It appears to connect okay, the client sends its header okay, but that's as far as it gets. The <code>onopen</code> or <code>onmessage</code> functions are never triggered at all.</p>
  
  <p>Here's the code for the Java server: </p>
  
  <pre><code>import java.net.*;
  import java.io.*;
  public class Server {
      static DataOutputStream out;
      public static void main(String[] args) {
          try {
              ServerSocket serverSocket = new ServerSocket(8112);
              System.out.println("Server Started");
              while(true) {
              Socket socket = serverSocket.accept();
              System.out.println("A client connected");
              out = new DataOutputStream(socket.getOutputStream());
  
              //Send a simple-as-can-be handshake encoded with UTF-8
              String handshake = "HTTP/1.1 101 Web Socket Protocol Handshake\r" +
              "Upgrade: WebSocket\r" +
              "Connection: Upgrade\r" +
              "WebSocket-Origin: http://localhost\r" +
              "WebSocket-Location: ws://localhost:8112/\r" +
              "WebSocket-Protocol: sample\r\n\r\n";
              out.write(handshake.getBytes("UTF8"));
              System.out.println("Handshake sent.");
  
              //Send message 'HI!' encoded with UTF-8
              String message = "HI!";
              out.write(0x00);
              out.write(message.getBytes("UTF8"));
              out.write(0xff);
              System.out.println("Message sent!");
  
              //Cleanup
              socket.close();
              out.close();
              System.out.println("Everything closed!");
          }
      } catch(Exception e) {
          System.out.println(e.getMessage());
      }
  }
  </code></pre>
  
  <p>And here's the code for the client:</p>
  
  <pre><code>&lt;html&gt;
    &lt;head&gt;
      &lt;meta charset="UTF-8"&gt;
      &lt;script&gt;
        function load() {
          var ssocket = new WebSocket("ws://localhost:8112/");
          socket.onopen = function(e) { alert("opened"); }
          socket.onclose = function(e) { alert("closed"); }
          socket.onmessage = function(e) { alert(e.data); }
        }
      &lt;/script&gt;
    &lt;/head&gt;
      &lt;body onload="load();"&gt;
      &lt;/body&gt;
  &lt;/html&gt;
  </code></pre>
  
  <p>Why won't <code>onopen</code> or <code>onmessage</code> trigger? I've tried a lot of different things I just can't seem to do it.</p>
  
  <p>What am I doing wrong?</p>