我想在作为服务器的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/