簡體   English   中英

將數據從Java程序發送到油脂應用程序?

[英]Sending data to greasemonkey application from java program?

我想在作為服務器的Java程序和作為客戶端的油脂單(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 wich之類的框架,該框架附帶了便捷的支持,可用於傳遞JSP視圖並封裝對輸出流的低級別訪問。

希望這可以幫助

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM