java - 从java程序向greasemonkey应用程序发送数据?

标签 java javascript network-programming greasemonkey

我想在作为服务器的java程序和作为客户端的greasemonkey(java脚本应用程序)之间创建连接。

我可以从客户端接收数据,但是如何将数据从服务器发送到客户端? 我在服务器中使用 OutputStream 将数据发送到客户端,但似乎不起作用。在客户端,我使用下面的代码来发送和接收数据:

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);
}
});

我在服务器中使用OutputStream,但似乎它不起作用或没有关联任何outputStream:(我尝试基本通信,但它不起作用并且只接收数据)

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);
     }}

如有任何建议,我们将不胜感激。

非常感谢。

最佳答案

由于您使用的是 Java,我猜您正在使用 Servlet 与服务器进行通信。

一个有效的示例可能如下所示:

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); 
}

对于更高级的输出,我会选择使用像 spring web mvc 这样的框架 方便地支持交付 JSP View 并封装对输出流的低级访问。

希望这有帮助

关于java - 从java程序向greasemonkey应用程序发送数据?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7201368/

相关文章:

java - 如何在处理中获取 rect() 的顶点?

java - 如何在 thymeleaf 模板中打印 java 对象?

java - MediaController 方法 adjustmentVolume 和 MediaSession

javascript - lightgallery.js slider 中的目标图像

javascript - 如何高亮:active element using javascript?

java - 树算法中水平上的齐次值

javascript - 使用javascript进行日期验证?

java - 用于高延迟连接的 sslsocket session 机制

c++ - 使用 netfilter 以原始形式获取数据包

c# - .Net Socket Read 功能阻塞问题