0

저는 여기 자바에서 매우 새로 왔습니다. 클라이언트와 서버 사이의 계산기처럼 작동하는 프로그램이 있습니다. 클라이언트는 다음과 같이 (+ 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 블록이 있으면 표시되지 않습니다. 빈 캐치 블럭이 없어야합니다. 그들이가 초기화되지 않습니다으로 actionPerformed()에서

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

회원 tfInputtfOutput 있습니다 null :로 변경합니다. 생성자 mathClient()은 로컬 변수 JTextField tfInputJTextField tfInput을 할당하고 관련 구성원을 큼지막하게 표시합니다.

끝없는 while 루프 이외에도 몇 가지 다른 즉각적인 문제가 있습니다. 스윙의 Event Dispatch Thread을 소켓으로 막지 마십시오. 보조 스레드 또는 SwingWorker 사용을 고려하십시오.

자세한 내용과 예는 Concurrency in Swing을 참조하십시오.

+0

다음은 간단한 클라이언트의 [예제] (http://stackoverflow.com/a/3245805/1048330)입니다. @trashgod에 의해 Swing을 사용하는 서버. +1 오래 전 :) – tenorsax