2011-08-26 107 views
0

我想創建一個作爲服務器的java程序和作爲客戶端的greasemonkey(java腳本應用程序)之間的連接。從java程序發送數據到greasemonkey應用程序?

我可以從客戶端接收數據,但是我應該怎麼做才能將數據從服務器發送到客戶端? 我在服務器中使用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); 
    }} 

任何建議將不勝感激。

非常感謝。

+0

的Greasemonkey的代碼是好的,你不表現出足夠的Java代碼,以幫助這一點。 –

+0

已添加java代碼。 – shohreh

+0

感謝您的Java代碼。問題是一個簡單的套接字不能完成Web響應所需的所有協議和轉換。使用一個servlet或一個標準的Web應用程序。 –

回答

1

正如你使用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視圖一個方便的支持和encapsules低電平訪問輸出流。

希望這有助於

+0

對不起。當我創建帖子時,問題被編輯。我會盡快修改我的答案。 – elfwyn

+0

感謝您的回覆。但我不使用servlet,我只是想創建一個服務器套接字並通過輸入和輸出流傳輸數據。我有簡單的輸入和輸出。但我無法與他們溝通。 – shohreh

+0

@shohreh,因此問題。有很多握手和包裝正在進行。你需要複製所有這些。使用servlet要聰明得多。 –

相關問題