run()方法不等待数据输入

时间:2016-04-06 22:04:29

标签: java server client

我正在尝试创建一个应用程序,您输入两个数字,数字将被解析并通过TCP协议发送到服务器,然后添加,返回,并设置为TextField。问题是,与BufferedReader流不同,run()方法不会等待输入数字。我目前正在使用DataInputStream和DataOutPutStream。

以下是以下代码!

public class Server implements Runnable {
         public Server(){

    }

    @Override
    public void run() {
        while (true) {
            try (ServerSocket serverSocket = new ServerSocket(1000);
                    Socket sSocket = serverSocket.accept();
    DataInputStream in = new DataInputStream(sSocket.getInputStream());
    DataOutputStream out = new DataOutputStream(sSocket.getOutputStream()))
            {
                System.out.println("Client connected.");
                Integer s1 = in.read();
                Integer s2 = in.read();
                Integer result = s1 + s2;
                out.write(result);



            }
            catch(IOException e) 
            {
                System.out.println(e.getMessage());
            }
        }
    }

}

客户端类:

bs.addActionListener(new ActionListener() {
       public void actionPerformed(ActionEvent ke) {

           n1 = Integer.parseInt(tf1.getText());
           n2 = Integer.parseInt(tf2.getText());
           tf1.setText(String.valueOf(n1));
           tf2.setText(String.valueOf(n2));


                  }
   });

      }
        @Override
        public void run() {
            try(Socket clientSocket = new Socket("localhost", 1000);
        DataInputStream in = new DataInputStream(clientSocket.getInputStream());
        DataOutputStream out = new DataOutputStream(clientSocket.getOutputStream()))

            {
    out.write(n1);
    out.write(n2);
    Integer rezultat = in.read();
    tf3.setText(String.valueOf(result));

            } catch (IOException ex) {
                System.out.println(ex.getMessage());
            }

        } 
    }

我通过主类和Threads开始。 先感谢您! :d

1 个答案:

答案 0 :(得分:0)

您的代码只需要进行一些更改即可解决此问题:首先,在您的主要内容中,替换

    Thread clientThread = new Thread( new Klijent() );
    clientThread.start();

    Thread serverThread = new Thread( new Server() );
    serverThread.start(); 
    new Klijent();

您希望服务器在后台运行,而不是在按钮事件处理程序中运行代码 - 服务器应该能够作为单独的程序运行。

其次,在Klijent构造函数中,删除

    Server s = new Server();

来自构造函数,因为它现在在main中完成,并替换

            s.run();

            run();

调用客户端的run方法,而不是服务器的。

如果赋值使用客户端线程发出请求,您还可以在按钮事件处理程序中添加第二个线程:

    public void actionPerformed(ActionEvent ke) {
        n1 = ...
        n2 = ...
        new Thread(Klijent.this).start(); // instead of this.run();
    }