我正在尝试在一个线程中循环执行writeUTF函数,尽管它处于while循环中,但它只运行一次。目的是循环通过一个大字节[]并以数据包形式发送它,而我只在writeUTF上运行一次。
我在循环外使用dos.flush()尝试了一个for循环,但这没有用。 writeUTF在while循环中仅运行一次。sys.out.print循环但不执行dos.writeUTF。
[如果我可以循环执行writeUTF函数,则每次迭代时,我可以发送巨型字节[]页面的不同部分,并获得一些睡眠!
这是我所拥有的:
服务器
public void runServer() throws IOException {
// server is listening on port 22122
ServerSocket ss = new ServerSocket(22122);
while (true) {
Socket s = null;
try {
s = ss.accept();
System.out.println("Server: A new client is connected : " + s);
// obtaining input and out streams
DataInputStream dis = new DataInputStream(s.getInputStream());
DataOutputStream dos = new DataOutputStream(s.getOutputStream());
// create a new thread object
System.out.println("Server: Creating Client Handler thread");
Thread t = new ClientHandler(s, dis, dos, page);
// Invoking the start() method
t.start();
} catch (Exception e) {
s.close();
e.printStackTrace();
}
}
}
ServerThread
public ServerThread(Socket s, DataInputStream dis, DataOutputStream dos, byte[] page) {
this.s = s;
this.dis = dis;
this.dos = dos;
this.page = page;
}
@Override
public void run() {
while (true) {
try {
dos.writeUTF("Repeated text");
} catch (IOException ex) {
Logger.getLogger(ServerThread.class.getName()).log(Level.SEVERE, null, ex);
}
}
}
输出:
Server: A new client is connected :
Server: Creating Client Handler thread
Client: Repeated text
在输出中,客户端显示它收到一次,但是我希望它继续接收。有什么帮助谢谢!
结果是我的while循环在客户端每次迭代都要求输入。一旦我把那条线放到循环之外,它就开始按我的期望循环。