2010-11-27 19 views
4

我正嘗試通過JSF創建帶有Web UI的套接字客戶端。在這個應用程序中,客戶端連接到服務器,將消息發送到服務器,從服務器接收消息並將其顯示在JSF頁面上。無法更新綁定到bean的組件的值

我設法連接到套接字服務器發送消息並接收消息。我無法在瀏覽器屏幕上顯示來自服務器的消息。當我在控制檯中打印時,它顯示正確。

我的JSF代碼:

<f:view> 
    <h:form binding="#{jsfSocketClient.form}"> 
     <a4j:keepAlive beanName="jsfSocketClient"/> 
     <h:outputText binding="#{jsfSocketClient.outputMessageBinding}"/> 
     <br/> 
     <h:inputText value="#{jsfSocketClient.inputFromUser}"/> 
     <br/> 
     <h:commandButton action="#{jsfSocketClient.sendMessage}" value="Send"/> 
    </h:form> 
</f:view> 

我的Java代碼:

public HtmlForm getForm() { 
    try { 
     socket = new Socket("192.168.1.115", 4444); 
     response = "Connection Success"; 
     outputMessageBinding.setValue("Connection Success"); 
     out = new PrintWriter(socket.getOutputStream(), true); 
     in = new BufferedReader(new InputStreamReader(socket.getInputStream())); 
    } catch (Exception e) { 
     e.printStackTrace(); 
     response = "You must first start the server application (YourServer.java) at the command prompt."; 
     outputMessageBinding.setValue(response); 
    } 
    return form; 
} 

public String sendMessage() { 
    outputMessageBinding.setValue(""); 
    try { 
     //String str = "Hello!\n"; 
     out.println(getInputFromUser()); 
     try { 
      String line = in.readLine(); 
      outputMessageBinding.setValue(line); 
      System.out.println("Text received :" + line); 
     } catch (IOException e) { 
      outputMessageBinding.setValue(e.getMessage()); 
      System.out.println("Read failed"); 
      System.exit(1); 
     } 
     //response = result.toString(); 

     if (getInputFromUser().equalsIgnoreCase("bye")) { 
      socket.close(); 
     } 
    } catch(Exception e) { 
     outputMessageBinding.setValue(e.getMessage()); 
     e.printStackTrace(); 
    } 
    return ""; 
} 

當我加載JSF頁面,如果服務器連接 '連接成功' 顯示正確,如果未連接錯誤信息顯示正確。當我嘗試在屏幕上顯示服務器消息時,它不會顯示。我怎樣才能解決這個問題?

更新 如果我創建新的outputtext組件並將消​​息從服​​務器設置爲它的值,則服務器消息顯示正確。我想知道爲什麼綁定在我的情況下不起作用?

回答

2

從JSF /網頁打開新套接字是一個主要的反模式。你爲什麼想這樣做?

您是否知道所有含義/限制/風險/問題?

更新:

從網頁創建插座有關於性能和安全性幾方面的含義。

如果您只是想練習Java套接字,最簡單的方法就是使用命令行客戶端。 http://download.oracle.com/javase/tutorial/networking/sockets/clientServer.html

無需爲JSF或任何其他Web技術增加額外的複雜性。您可以擁有沒有Web服務器的套接字。 (實際上socket早在http之前就存在了)。

+0

感謝您查看我的問題。我在Java中練習套接字應用程序。因此,首先我創建了一個基於JSF的基於Web的客戶端。您是否意味着創建基於Web的套接字客戶端是有風險的?我不知道這裏的問題。 – mvg 2010-12-01 11:08:49

相關問題