0

I try to communicate between javascript and java. My script javascript send a message to java and java send a response.

javascript part:

    var xmlhttp = new XMLHttpRequest();
    xmlhttp.onreadystatechange=function()
      {
      if (xmlhttp.readyState==4)
        {
        alert(xmlhttp.responseText);
        }
      }
    var s = "LIGNE \n 2 \n il fait beau \nEND\n";
    xmlhttp.open("POST","http://localhost:6020",true);
    xmlhttp.send(s);

java part:

    try {
        serverSocket = new ServerSocket(6020);
    } catch (IOException e) {
        System.err.println("Could not listen on port: 6020.");
        System.exit(-1);
    }
    serverSocket.accept()
    BufferedReader br = new BufferedReader(
                new InputStreamReader(socket.getInputStream()));
    BufferedWriter bw =  new BufferedWriter(
                new OutputStreamWriter(socket.getOutputStream()));
    String ligne = "";
    while(!(ligne = plec.readLine()).equals("END")){
        System.out.println(ligne);
    }
    bw.write("Il fait beau\n");
    bw.flush();
    bw.close();
    plec.close();
    socket.close();

output java :

POST / HTTP/1.1
Host: localhost:6020
User-Agent: Mozilla/5.0 (X11; Ubuntu; Linux x86_64; rv:13.0) Gecko/20100101 Firefox/13.0.1
Accept: text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8
Accept-Language: fr,fr-fr;q=0.8,en-us;q=0.5,en;q=0.3
Accept-Encoding: gzip, deflate
Connection: keep-alive
Referer: http://localhost:8080/test.html
Content-Length: 30
Content-Type: text/plain; charset=UTF-8
Origin: http://localhost:8080
Pragma: no-cache
Cache-Control: no-cache

LIGNE 
 2 
 il fait beau 

So, I receive correctly the message send by javascript but the alert his always empty. How to response at this message? I try a lot of possiblity but they don't work. And I don't want to use the servlet, it's to heavy to do that.

Thanks.

Edit:

I did this :

bw.write("HTTP/1.1 200 OK\r\n"+
        "Content-Type: text/html; charset=utf-8\r\n"+
        "Content-Length: 13\r\n\r\n" +
        "il fait beau\n");

and this:

String data = "il fait beau \n";

StringBuilder builder = new StringBuilder();

builder.append("HTTP/1.1 200 OK\r\n");
builder.append("Content-Type: text/html; charset=utf-8\r\n");
builder.append("Content-Length:" + data.length() + "\r\n\r\n");
builder.append(data);
bw.write(builder.toString());

But the alert remain empty. Maybe it's a problem in the javascript.

AnthonyMaia
  • 27
  • 1
  • 9

2 Answers2

3

The javascript needs to see a full HTTP response. Merely sending back characters to it, makes it discard the reply as it is an invalid HTTP response.

In your java code, send back something like this

HTTP/1.1 200 OK
Content-Type: text/html; charset=utf-8
Content-Length: <length of data>

---data here---

Reference

Something like:

StringBuilder builder = new StringBuilder();
builder.append("HTTP/1.1 200 OK\r\n");
builder.append("Content-Type: text/plain; charset=utf-8\r\n");
builder.append("Content-Length:" + data.length() + "\r\n\r\n);
builder.append(data);
bw.write(builder.toString());
Anirudh Ramanathan
  • 46,179
  • 22
  • 132
  • 191
  • How do I build a complete HTTP response? – AnthonyMaia Jul 17 '12 at 12:04
  • You need to add at least `HTTP/1.1 200 OK` because only then, `readyState==4` in JavaScript and a `Content-Length` for your response. (Or you send a chunked response but I guess this is too complicated in your case.) – 1' OR 1 -- Jul 17 '12 at 12:07
  • @Birk what's a chunked response? – AnthonyMaia Jul 17 '12 at 12:14
  • If you send `Content-Length` you have to know the length of your response before. If you do not know before, you can make use of `Content-Transfer-Encoding: chunked` (http://en.wikipedia.org/wiki/Chunked_transfer_encoding) – 1' OR 1 -- Jul 17 '12 at 12:16
2

Try:

bw.write("HTTP/1.1 200 OK\r\n"+
            "Content-Type: text/html; charset=utf-8\r\n"+
            "Content-Length: 13\r\n\r\n" +
            "il fait beau\n");

HTTP-Headers are separated by \r\n (CRLF). Headers and body is spearated by \r\n\r\n.

Note that you set the length to 13 because you also have to count the \n at the end of your string.

EDIT: It does not work because of the cross-domain-policy. http://localhost:6020 is not the same port as the website which executes your JavaScript and so the xmlhttprequest might not be delivered.

1' OR 1 --
  • 1,694
  • 1
  • 16
  • 32
  • Thanks, but always nothing in the alert. – AnthonyMaia Jul 17 '12 at 12:17
  • Sorry, I have currently `Content-Length: 13\r\n\r\n+` in my code. Remove the `+`. This is a typing mistake. I have changed it in my example. Then it should work. – 1' OR 1 -- Jul 17 '12 at 12:22
  • It's not the problem, I remove it but always nothing. – AnthonyMaia Jul 17 '12 at 12:32
  • +1 :D That didn't occur to me! @AnthonyMaia, is the site from which you are executing the XMLHttp request also on localhost? – Anirudh Ramanathan Jul 17 '12 at 12:41
  • Also if it was, it cannot be the same port because already his Java-program is using it. I also cannot find another reason why it should not work. But I first didn't think of it either^^ – 1' OR 1 -- Jul 17 '12 at 12:42
  • This would be difficult... You could write a simple proxy using curl, if you have PHP installed on your primary server. You could also take a look there: http://stackoverflow.com/questions/787067/is-there-a-xdomainrequest-equivalent-in-firefox Try adding a `Access-Control-Allow-Origin: *\r\n` to the response headers of your Java application and see if it works then. – 1' OR 1 -- Jul 17 '12 at 12:47