简体   繁体   中英

Sending data to greasemonkey application from java program?

I want to create a connection between a java program as a server and a greasemonkey(java script application) as a client.

I can recieve data from client, but what should I do to send data from server to client? I'm using OutputStream in the server to send data to the client, but it seems it doesn't work. On the client side I use code below to send and receive data:

GM_xmlhttpRequest({
method: 'POST',
url: "http://localhost:8888",

headers: {
    'Content-type' : 'application/x-www-form-urlencoded',
},
data : 'page_contents=' + window.location,
onload : function(responseDetails) {
    alert('Request for Atom feed returned ' + responseDetails.status +
          ' ' + responseDetails.statusText + '\n\n' +
          'Feed data:\n' + responseDetails.responseText);
}
});

I use OutputStream to in server but seem's it doesn't work or doesn't associate any outputStream:(i try the basic communication, but it didn't work and only recieves data)

ServerSocket srvr = new ServerSocket(8888);
     Socket skt = srvr.accept();

     BufferedReader in = new BufferedReader(new     InputStreamReader(skt.getInputStream()));
     System.out.print("Received string: '");
     String input="";
     while (!in.ready()) {}
     while((input = in.readLine())!=null){
         System.out.println("-"+input); // Read one line and output it
     }        
     in.close();
     //now I want to send some data to greasmonkey. 
     PrintWriter out = new PrintWriter(skt.getOutputStream(), true);
     System.out.print("Sending string: '" + data + "'\n");
     //the line above, never has printed in console. i don't know why?
     out.print(data);
     }}

Any suggestion would greatly be appreciated.

Thanks a lot.

As you are using Java I guess you are using a Servlet to communicate with the Server.

A valid example could look something like this:

public class myServlet extends HttpServlet {
  public void doPost(HttpServletRequest request, 
     HttpServletResponse response) throws ServletException, IOException
{
  response.setContentType("text/html"); 

  // for text data you could write something like this:
  PrintWriter output = response.getWriter();
  output.println("Hello, World\n"); 

  // for binary data you could use the output stream this way:
  // Object binary_data = new Object();
  // ServletOutputStream output = response.getOutputStream();
  // output.print(binary_data); 
}

For more advanced output I would choose to use a framework like spring web mvc wich comes with a handy support for delivering JSP views and encapsules low level access to the output stream.

Hope this helps

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM