我正在尝试将此scriptlet code转换为JSF类。
观看代码
<f:view>
<h:form binding="#{jsfSocketClient.form}">
<h:outputText binding="#{jsfSocketClient.text}"/>
</h:form>
</f:view>
和java代码
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;
}
当我运行scriptlet代码时,我得到了答案 “服务器得到了这个:你好!”
当我运行JSF代码时,我没有收到此回复。请纠正我的错误
提前致谢
答案 0 :(得分:3)
我纠正了我的回答。问题是输入流的处理。这是固定代码:
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);