I've got the following setup: Index.html (WebPage)
<div id="sse">
<a href="javascript:WebSocketTest()">Run WebSocket</a>
<a href="javascript:websocketsend()">Send message</a>
</div>
<script type="text/javascript">
var ws;
function WebSocketTest()
{
if ("WebSocket" in window)
{
console.log("WebSocket is supported by your Browser!");
// Let us open a web socket
ws = new WebSocket("ws://localhost:6790/");
ws.onopen = function()
{
// Web Socket is connected, send data using send()
ws.send("Hello_World!");
console.log("Message is sent...");
};
ws.onmessage = function (evt)
{
var received_msg = evt.data;
console.log("Message is received...");
};
ws.onclose = function(event)
{
var reason;
// websocket is closed.
console.log(event.code);
console.log("closed.")
}
ws.onerror = function (evt)
{
console.log(evt);
}
}
else
{
// The browser doesn't support WebSocket
console.log("WebSocket NOT supported by your Browser!");
}
}
</script>
Java Socket Server
private String decodeMessage(InputStream in) {
Main.debug(in + "");
try {
in.skip(2);
ArrayList<Byte> keys = new ArrayList<Byte>();
for(int i = 0; i < 4; i++){
int r = in.read();
Main.debug("added: " + r);
keys.add((byte) r);
}
ArrayList<Byte> encoded = new ArrayList<Byte>();
for(int i = 0; i < in.available(); i++){
int r = in.read();
Main.debug("added2: " + r);
encoded.add((byte) r);
}
ArrayList<Byte> decoded = new ArrayList<Byte>();
for(int i = 0; i < encoded.size(); i++){
decoded.add((byte) (encoded.get(i) ^ keys.get(i & 0x3)));
Main.debug("Decoded: " + (encoded.get(i) ^ keys.get(i & 0x3)));
}
Main.debug("Total: " + decoded);
String s = new String(toByteArray(decoded), "US-ASCII");
Main.debug("Text: " + s);
} catch(IOException e) {
}
return null;
}
public static byte[] toByteArray(List<Byte> in) {
final int n = in.size();
byte ret[] = new byte[n];
for (int i = 0; i < n; i++) {
ret[i] = in.get(i);
}
return ret;
}
The problem is that the message get's through fine, however I get this as output (apart from "Added" & "Decoded" debug messages,
[19:42:02 INFO]: Total: [72, 101, 108, 108, 111, 95] [19:42:02 INFO]: Text: Hello_
So "World!" is lost, even if I replace the _ with a space. Is there something I'm overlooking?
I hope someone can give me a hint here. Thanks in advance!