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 onopen or onmessage functions are never triggered at all.
Here’s the code for the Java server:
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());
}
}
And here’s the code for the client:
<html>
<head>
<meta charset="UTF-8">
<script>
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); }
}
</script>
</head>
<body onload="load();">
</body>
</html>
Why won’t onopen or onmessage trigger? I’ve tried a lot of different things I just can’t seem to do it.
What am I doing wrong?
There’s a challenge-response aspect to the protocol that you appear to be missing – the client sends two extra headers and some random data:
and the server is expected to derive a MD5 response by:
producing a response like:
This process is designed to prevent non-WebSocket requests from being handled by WebSocket servers – see section 1.3 of the WebSocket protocol for details.