[英]Looping DataOutputStream writeUTF in thread
I'm trying to loop the writeUTF function in a thread and it only runs once despite it being in a while loop.我试图在一个线程中循环 writeUTF 函数,尽管它处于 while 循环中,但它只运行一次。 The purpose is to loop through a large byte[] and send it in packets and i'm stuck on writeUTF only running once.
目的是遍历一个大字节 [] 并以数据包的形式发送它,我被困在 writeUTF 只运行一次。
I tried a for loop with dos.flush() outside the loop and that didn't work.我在循环外尝试了一个带有 dos.flush() 的 for 循环,但没有奏效。 writeUTF only runs once in the while loop.
writeUTF 只在 while 循环中运行一次。 A sys.out.print loops but not dos.writeUTF.
sys.out.print 循环但不循环 dos.writeUTF。
If I can loop the writeUTF function I can send a different subsection of the giant byte[] page with each iteration and get some sleep!如果我可以循环 writeUTF 函数,我可以在每次迭代时发送巨型字节 [] 页面的不同子部分,然后睡一觉!
Here's what I have:这是我所拥有的:
Server服务器
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);
}
}
}
Output:输出:
Server: A new client is connected :
Server: Creating Client Handler thread
Client: Repeated text
In the output, the Client shows it received it once, but I want it to keep receiving.在输出中,客户端显示它收到了一次,但我希望它继续接收。 Anything helps thank you!
有什么帮助谢谢!
Turns out my while loop on the Client side was asking for input every iteration.原来我在客户端的 while 循环每次迭代都要求输入。 Once I took that line and put it outside my loop it began looping how I expected it to.
一旦我把那条线放在我的循环之外,它就开始按照我的预期循环。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.