gpt4 book ai didi

java - 如何将输入从 GUI 传递到客户端而不是服务器?

转载 作者:行者123 更新时间:2023-11-30 04:08:14 24 4
gpt4 key购买 nike

我对 Java 很陌生。我有一个程序,它的作用就像客户端和服务器之间的计算器。客户端将像这样输入他们的函数(+ 1 2)。但现在我给它一个 GUI 界面。如何将用户输入从 GUI 传递到客户端控制台,然后将其传递到服务器进行计算,然后将其显示回 UI?我只需要一些简单的东西。

客户端

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);
}
}
}

最佳答案

问题之一是 actionPerformed() 中的 NullPointerException。但是,它不可见,因为您有一个空的 catch block 。永远不应该有空的 catch block 。将其更改为:

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

成员 tfInputtfOutputactionPerformed() 中为 null,因为它们从未初始化。构造函数 mathClient() 分配局部变量 JTextField tfInputJTextField tfInput 并覆盖相关成员。

除了无休止的 while 循环之外,还有其他几个迫在眉睫的问题。您不应该阻止 Swing 的 Event Dispatch Thread带 socket 。考虑使用辅助线程或 SwingWorker。

参见Concurrency in Swing了解详细信息和示例。

关于java - 如何将输入从 GUI 传递到客户端而不是服务器?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20244601/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com