[英]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.