Java客户端/服务器 - 使用AWT的2个数字的总和

时间:2015-08-03 11:06:40

标签: java awt client-server

这是我坚持的练习:

我必须使用AWT文本字段插入两个整数,然后单击按钮打印它们的总和。解析值和总和计算需要在服务器端完成,然后发送回客户端 我如何返回结果?我选择了正确的方法吗?!这就是我所做的,所以如果有人可以提供帮助并给出一些建议,我将不胜感激。

服务器代码:

public class Server {
public static void main(String args []) throws IOException{


    try (ServerSocket s1 = new ServerSocket(1342);
        Socket ss1 = s1.accept();
        BufferedReader b = new BufferedReader(new InputStreamReader(ss1.getInputStream()));
        BufferedOutputStream bos = new BufferedOutputStream(ss1.getOutputStream());
        ){

            int res = 0;
            String line = b.readLine();
            while(line != null && !line.equals("")){
                int num1 = Integer.parseInt(b.readLine());
                int num2 = Integer.parseInt(b.readLine());
                res = num1 + num2;



            }
            bos.write((res+"").getBytes()); 
     }
   } 
}

这是一个客户端代码,在按钮操作事件下编写:

private void calculate_btnActionPerformed(java.awt.event.ActionEvent evt) {                                              
   try (
       Socket s = new Socket("127.0.0.1", 1342);           
       BufferedReader br = new BufferedReader(new InputStreamReader(s.getInputStream()));
       BufferedOutputStream bos = new BufferedOutputStream(s.getOutputStream());
        ){
       // num1 and num2 are text fields
       bos.write((num1.getText()).getBytes()); 
       bos.write((num2.getText()).getBytes());
       bos.flush();


       String res = br.readLine();
       while (res != null){
           res=br.readLine();
       result.setText(res);  // label where result should be printed
       }           


    } catch (IOException ex) {
        Logger.getLogger(SumUI.class.getName()).log(Level.SEVERE, null, ex);
    }

0 个答案:

没有答案