Unable to update value of component which is bound to bean
I am trying to create a socket client with a web UI by JSF. In this application, the client is connecting to the server, sends the message to the server, receives the message from the server and displays it on the JSF page.
I managed to connect to the socket server send message and receive message. I am unable to show the message from server in the browser screen. When I print in the console, it displays correct.
My jsf code is:
<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>
And my java code is:
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 = "Yo开发者_如何转开发u 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 "";
}
When I load the jsf page, if the server is connected 'Connection Success' is shown correctly, if not connected the error message is shown correctly. When I try to display the server message in the screen, it is not getting displayed. How can I fix this?
Update If I create new outputtext component and set the message from server as its value, then the Server message is getting displayed correctly. I want to know why binding did not work in my case?
Opening new sockets from a JSF/Webpage is a major anti-pattern. Why do you want to do this?
Are you aware of all the implications/limitations/risks/problems?
Update:
Creating sockets from web pages has several implications with regards to performance and security.
If you just want to practice Java sockets the simplest way is with command line clients. http://download.oracle.com/javase/tutorial/networking/sockets/clientServer.html
No need to add extra complexity with JSF or any other web technology. You can have sockets without a web server. (In fact sockets existed long before http).
精彩评论