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.

8
  • Update the output java : section of your question to show what happens when you send the new request. Commented Jul 17, 2012 at 12:26
  • @DarkXphenomenon the output didn't change. Commented Jul 17, 2012 at 12:30
  • Try opening http://localhost:6020 in your browser, to debug this. You should see the text displayed in the browser, if your response is correct. You can also debug the response, using LiveHttpHeaders addon in firefox Also, note the edit to my answer. Change the content-type to text/plain. Commented Jul 17, 2012 at 12:32
  • The content-type shouldn't be the issue... Commented Jul 17, 2012 at 12:35
  • @DarkXphenomenon I just open the localhost:6020 in a browser and "il fait beau" appeared. Commented Jul 17, 2012 at 12:38

2 Answers 2

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());
Sign up to request clarification or add additional context in comments.

4 Comments

How do I build a complete HTTP response?
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.)
@Birk what's a chunked response?
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 (en.wikipedia.org/wiki/Chunked_transfer_encoding)
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.

6 Comments

Thanks, but always nothing in the alert.
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.
It's not the problem, I remove it but always nothing.
+1 :D That didn't occur to me! @AnthonyMaia, is the site from which you are executing the XMLHttp request also on localhost?
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^^
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.