我是网络编程新手并写了一个聊天客户端。它几乎正常工作,但是当我突然添加if子句in.hasnext
时,即使我的服务器实际上发送了一些东西,它也会返回false。
使用if子句:
@Override
public void run() {
while(!server.isClosed()){
if(ChatClient.WriteListener.message!=null){
String m = ChatClient.WriteListener.message;
out.println(m);
ChatClient.WriteListener.message = null;
}
if(in.hasNext()){
System.out.println("hab");
String message = in.next();
textPane.setText(textPane.getText()+"\n"+message.replaceAll("_", " "));
}
out.flush();
}
System.out.println("closed");
}
没有if子句
public void run() {
while(!server.isClosed()){
out.println(ChatClient.WriteListener.message);
if(in.hasNext()){
System.out.println("hab");
String message = in.next();
textPane.setText(textPane.getText()+"\n"+message.replaceAll("_", " "));
}
}
System.out.println("closed");
}
创建进出:
public UserThread(Socket s){
server = s;
try {
out = new PrintWriter( server.getOutputStream(), true );
in = new Scanner( server.getInputStream() );
} catch (IOException e) {
e.printStackTrace();
}
}
WriteListener
public static class WriteListener implements ActionListener {
JTextField text;
static String message;
public WriteListener(JTextField jtf){
text = jtf;
}
public void actionPerformed(ActionEvent ev) {
message = text.getText();
}
}
答案 0 :(得分:1)
您的代码存在问题:
if (ChatClient.WriteListener.message!=null){
String m = ChatClient.WriteListener.message;
out.println(m);
ChatClient.WriteListener.message = null;
}
您的out
是实例PrintWriter(OutputStream out, boolean autoFlush)
。当您在第一个out.println(m)
语句if
中调用PrintWriter
时,在Socket上刷新缓冲区/流,导致您的第二个if(in.hasNext())
语句返回false
因为您的I / O套接字由PrintWriter
自动关闭。您需要在true
的初始化中更改/删除PrintWriter
,如下所示:
try {
out = new PrintWriter( server.getOutputStream());
in = new Scanner( server.getInputStream() );
} catch (IOException e) {
e.printStackTrace();
}