我想通过BufferedWritter写入数据,一切正常,但是我无法在需要时发送它,如果我在while(true)部分中重复发送而不跳过循环,它就可以正常工作。
如您所见,我想发送sendData(“ 000”),但它不会发送(代码正在运行),但是当我跳过if和but sendData进入while并重复发送时,发送了它。 / p>
public class Connection {
public Socket connection;
public BufferedReader is;
public BufferedWriter os;
public long logged;
public Server server;
public Connection(Server server, Socket connection) {
this.connection = connection;
this.server = server;
resetStream();
try {
String s = is.readLine();
if(!s.equals(Main.version)) {
connection.close();
is.close();
os.close();
System.out.println(connection.getRemoteSocketAddress().toString()+" sai phien ban");
return;
}
System.out.println(connection.getRemoteSocketAddress().toString()+" da ket noi voi phien ban "+s);
} catch (IOException e) {
e.printStackTrace();
}
logged = System.currentTimeMillis();
inputListener();
}
public void inputListener() {
new Thread() {
public void run() {
while(true) {
try {
String cmd = is.readLine();
if(cmd == null) continue;
System.out.println("["+connection.getRemoteSocketAddress()+"] "+cmd);
if(cmd.split(" ")[0].equals("REGISTER")) {
if(server.database.registerUser(cmd.replace("REGISTER ","")) == 1)
System.out.println("["+connection.getRemoteSocketAddress()+"] da dang ky thanh cong voi user "+cmd.replace("REGISTER ",""));
else sendData("000");
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
}.start();
}
public void sendData(String string) {
try {
os.write(string);
os.newLine();
os.flush();
} catch (IOException e) {
e.printStackTrace();
}
}
public void resetStream() {
try {
if(os != null) os.close();
if(is != null) is.close();
is = new BufferedReader(new InputStreamReader(connection.getInputStream()));
os = new BufferedWriter(new OutputStreamWriter(connection.getOutputStream()));
} catch (IOException e) {
e.printStackTrace();
}
}
}