0

我在這裏對Java很陌生。我有一個在客戶端和服務器之間像計算器一樣的程序。客戶端將輸入他們的功能(+ 1 2)。但現在我給它一個GUI界面。我如何將用戶輸入從GUI傳遞到客戶端控制檯,然後將其傳遞給服務器來計算並顯示回UI?我只需要一些簡單的東西。如何將輸入從GUI傳遞給客戶端而不是服務器?

客戶

import java.io.*; 
import java.net.Socket; 
import java.util.Scanner; 

import java.awt.*;  // using AWT containers and components 
import java.awt.event.*; // using AWT events and listener interfaces 
import javax.swing.*; 

public class mathClient extends JFrame implements ActionListener { 
    private int count = 0; 
    private JFrame frame; 
    private JPanel panel; 

    private JLabel lblInput; 
    private JLabel lblOutput; 
    private JTextField tfInput; 
    private JTextField tfOutput; 


      /** The entry main() method */ 
    public static void main(String[] args) throws Exception { 
    // Invoke the constructor to setup the GUI, by allocating an instance 
     mathClient app = new mathClient(); 

    } 

      public void actionPerformed(ActionEvent event){ 
       try{ 
       Socket clientSocket = new Socket("localhost", 50000); 
       BufferedReader inFromServer = new BufferedReader(new InputStreamReader(clientSocket.getInputStream())); 
       DataOutputStream outToServer = new DataOutputStream(clientSocket.getOutputStream()); 
       PrintWriter print = new PrintWriter(clientSocket.getOutputStream(), true); 

       String input; 
       String output; 

       //String input; 

       while(true){ 
        //System.out.println("Please enter your function and numbers:"); 
        input = tfInput.getText(); 

        print.println(input); 

        if(input.equals("disconnect")){ 
         break; 
        } 

        output = inFromServer.readLine(); 
        System.out.println(output); 
        tfOutput.setText(output); 


       } 
       clientSocket.close(); 
       } 
       catch (Exception e) 
       { 
       } 


     } 


    public mathClient() 
    { 
     Container contentPane = getContentPane(); 
     contentPane.setLayout(new BorderLayout()); 

     JFrame frame = new JFrame("Calculator"); 
     JPanel panel = new JPanel(); 

     JLabel lblInput = new JLabel("Input: "); 

     JLabel lblOutput = new JLabel("Output: ");  

     JTextField tfInput = new JTextField(); 
     tfInput.setEditable(true); 
    // tfInput.addActionListener(); 

     JTextField tfOutput = new JTextField(); 
     tfOutput.setEditable(false); 

     JButton btnCalculate = new JButton("Calculate"); 
     btnCalculate.addActionListener(this); 

     frame.add(panel); 
     panel.add(lblInput); 
     panel.add(tfInput); 
     panel.add(lblOutput); 
     panel.add(tfOutput); 
     panel.add(btnCalculate); 

     tfInput.setPreferredSize(new Dimension(200, 30)); 
     tfOutput.setPreferredSize(new Dimension(200, 30)); 

     frame.pack(); 
     frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); 
     frame.setSize(230,250); 
     frame.setResizable(false); 
     frame.setVisible(true);  
    } 

} 

服務器

import java.io.*; 
import java.net.ServerSocket; 
import java.net.Socket; 
import java.util.Scanner; 

// Takes in a mathematical operation and the operands from a client and returns the result 
// Valid operations are add, sub, multiply, power, divide, remainder, square 
public class mathServer 
{ 
    public static void main(String [] args) throws IOException 
    { 
     ServerSocket welcomeSocket = new ServerSocket(50000); //put server online 
     while(true) 
     { 
      System.out.println("Waiting for connection..."); 
      Socket connectionSocket = welcomeSocket.accept(); //open server to connections 
      System.out.println("Connection accepted"); 
      process(connectionSocket);     //process accepted connection 
      System.out.println("Connection closed"); 
     } 
    } 

    //BufferedReader(Reader r) 
    static void process(Socket welcomeSocket) throws IOException 
    { 
     InputStream in = welcomeSocket.getInputStream(); 
     BufferedReader buffer = new BufferedReader(new InputStreamReader(in)); 
     OutputStream out = welcomeSocket.getOutputStream(); 
     PrintWriter print = new PrintWriter(out, true);  

     String input = buffer.readLine(); //get user input from client     

     while(input != null && !input.equals("disconnect")) //check for input, if bye exit connection 
     {    
      int answer = operate(input); //perform desired operation on user input 
      print.println(answer);   //print out result 
      input = buffer.readLine();  //get next line of input     
     } 
     welcomeSocket.close(); 
    } 

    //Talk to the client   
    static int operate(String s) 
    { 
     System.out.println(s); //check if same as client input 

     Scanner scanner = new Scanner(s); 
     char option = scanner.next().charAt(0); //gets desired operation 

     System.out.println(option); //checks for correct operation 

     switch (option) { 
      case '+': 
       return (scanner.nextInt() + scanner.nextInt()); 
      case '-': 
       return (scanner.nextInt() - scanner.nextInt()); 
      case '*': 
       return (scanner.nextInt() * scanner.nextInt()); 
      case '^': 
       return (int) Math.pow(scanner.nextInt(), scanner.nextInt()); 
      case '/': 
       return scanner.nextInt()/scanner.nextInt(); 
      case '%': 
       return scanner.nextInt() % scanner.nextInt(); 
      case 's': 
       return (int) Math.pow(scanner.nextInt(), 2); 
      default: 
       return (int) Math.pow(scanner.nextInt(), 3); 
     }      
    } 
} 
+0

什麼不起作用? –

+0

@peekillet它不會將輸入傳遞給服務器。和我不知道如何通過它從服務器返回並返回給客戶機並在UI –

回答

1

其中一個問題是actionPerformed()NullPointerException。但是由於您有空的catch塊,因此它不可見。你永遠不應該有空的catch塊。將其更改爲:

catch (Exception e) { 
    e.printStackTrace(); 
} 

actionPerformed()成員tfInputtfOutputnull,因爲他們永遠不會初始化。構造函數mathClient()分配局部變量JTextField tfInputJTextField tfInput並遮蓋相關成員。

除了無盡的while循環之外,還有幾個其他的直接問題。您不應該用套接字阻止Swing的Event Dispatch Thread。考慮使用輔助線程或SwingWorker。

有關詳細信息和示例,請參閱Concurrency in Swing

+0

這裏顯示它是一個[示例](http://stackoverflow.com/a/3245805/1048330)一個簡單的客戶的-server使用@trashgod的Swing。 +1很久以前:) – tenorsax

相關問題