Search code examples
javajspjsfscriptlet

convert from scriptlet to JSF managed bean problem


I am trying to convert this scriptlet code to JSF class.

The view code

<f:view>
<h:form binding="#{jsfSocketClient.form}">
    <h:outputText binding="#{jsfSocketClient.text}"/>

</h:form>
</f:view>

and the java code

private HtmlForm form = new HtmlForm();
private HtmlOutputText text = new HtmlOutputText();

public HtmlForm getForm() 
{
    System.out.println("instance:  "+FacesContext.getCurrentInstance().getResponseWriter());
    ResponseWriter writer = (FacesContext.getCurrentInstance()).getResponseWriter();  
    try{

        int character;
        Socket socket = new Socket("127.0.0.1", 8765);

        InputStream inSocket = socket.getInputStream();
        OutputStream outSocket = socket.getOutputStream();

        String str = "Hello!\n";
        byte buffer[] = str.getBytes();
        outSocket.write(buffer);
        char characters = 0;
        while ((character = inSocket.read()) != -1) {
            text.setValue((char)character);
            //writer.write((char)character);
            //characters += (char)character;
        }
        //text.setValue(characters);
        if(str.equalsIgnoreCase("bye"))
                {
                    socket.close();
                }
    }
    catch(Exception e)
    {
        e.printStackTrace();
        text.setValue("You must first start the server application (YourServer.java) at the command prompt.");          
    }
    return form;
}

When I run scriptlet code, I am getting the answer as "The server got this: Hello! "

When I run the JSF code I am not getting this reply. Please correct my mistake

Thanks in advance


Solution

  • I correct my answer. The problem is the processing of the input stream. Here is the fixed code:

        String response = "";
        try {
    
            Socket socket = new Socket("127.0.0.1", 8765);
    
            Reader reader = new InputStreamReader(socket.getInputStream());
            OutputStream outSocket = socket.getOutputStream();
    
            String str = "Hello!\n";
            byte buffer[] = str.getBytes();
            outSocket.write(buffer);
    
            CharArrayWriter result = new CharArrayWriter();
            char[] buf = new char[4096];
            int charsRead = 0;
            while ((charsRead = reader.read(buf)) != -1) {
                result.write(buf, 0, charsRead);
            }
            response = result.toString();
    
            if (str.equalsIgnoreCase("bye")) {
                socket.close();
            }
        } catch (Exception e) {
            e.printStackTrace();
            response = "You must first start the server application (YourServer.java) at the command prompt.";
        }
        text.setValue(response);