【问题标题】:Looping DataOutputStream writeUTF in thread在线程中循环 DataOutputStream writeUTF
【发布时间】:2019-12-05 04:28:15
【问题描述】:

我正在尝试在线程中循环 writeUTF 函数,尽管它处于 while 循环中,但它只运行一次。目的是循环一个大字节[]并将其以数据包的形式发送,我被卡在 writeUTF 上,只运行一次。

我在循环外尝试了一个带有 dos.flush() 的 for 循环,但没有成功。 writeUTF 仅在 while 循环中运行一次。 一个 sys.out.print 循环,但不是 dos.writeUTF。

如果我可以循环 writeUTF 函数,我可以在每次迭代时发送巨型 byte[] 页面的不同小节并获得一些睡眠!

这是我所拥有的:

服务器

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

在输出中,客户端显示它收到了一次,但我希望它继续接收。 有什么帮助谢谢!

【问题讨论】:

  • 向我们展示您的客户和您的证据。此循环连续发送。

标签: java multithreading sockets utf dataoutputstream


【解决方案1】:

原来我在客户端的 while 循环每次迭代都要求输入。一旦我把那条线放在我的循环之外,它就开始按照我的预期循环。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2015-03-01
    • 2016-05-26
    • 1970-01-01
    • 1970-01-01
    • 2014-12-18
    相关资源
    最近更新 更多