繁体   English   中英

在线程中循环 DataOutputStream writeUTF

[英]Looping DataOutputStream writeUTF in thread

我试图在一个线程中循环 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();
        }
    }
}

服务器线程

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 循环每次迭代都要求输入。 一旦我把那条线放在我的循环之外,它就开始按照我的预期循环。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM