我有一个主类,其中包含一个启动与服务器连接的方法。 在JFrame类中,我有一个按钮注册,当按下它时,它将检索用户输入并将其发送到服务器。 我的问题是,由于从main方法传递变量的错误,与服务器的连接无法正常工作。 我尝试在JFrame类中声明连接的变量,并在构造函数中将它们分配给主类变量,但这也不起作用。
主要课程:
public class TCPClient {
Socket clientSocket;
DataOutputStream outToServer;
BufferedReader inFromServer;
String test;
public void start() throws Exception{
clientSocket= new Socket("localhost", 6789);
outToServer= new DataOutputStream(clientSocket.getOutputStream());
inFromServer= new BufferedReader(new InputStreamReader(clientSocket.getInputStream()));
test="abc";
}
public static void main(String[] args) throws Exception {
TCPClient c=new TCPClient ();
c.start();
NewJFrame j=new NewJFrame();
j.setVisible(true);
}}
JFrame类:
public class NewJFrame extends javax.swing.JFrame {
JTextField username = new JTextField();
JTextField name = new JTextField();
JTextField Email = new JTextField();
JTextField Address = new JTextField();
JTextField password = new JPasswordField();
BufferedReader inFromUser;
Socket clientSocket;
DataOutputStream outToServer;
BufferedReader inFromServer;
String test;
public NewJFrame() throws Exception {
TCPClient c=new TCPClient();
c.start();
inFromServer=c.inFromServer;
clientSocket=c.clientSocket;
outToServer=c.outToServer;
inFromServer=c.inFromServer;
test=c.test;
initComponents();
}
private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {
System.out.print(test);
Object[] message = {
"Full Name:", name,
"Email:", Email,
"Address:", Address,
"Username:", username,
"Password:", password
};
int option = JOptionPane.showConfirmDialog(null, message,"Sign in",JOptionPane.OK_CANCEL_OPTION);
try{
System.out.print(test);
outToServer.writeBytes("signup"+ '\n');
outToServer.writeBytes(name.getText() + '\n');
outToServer.writeBytes(Email.getText() + '\n');
outToServer.writeBytes(Address.getText() + '\n');
outToServer.writeBytes(username.getText() + '\n');
outToServer.writeBytes(password.getText() + '\n');
JOptionPane.showMessageDialog(null, inFromServer.readLine());
clientSocket.close();
}
catch(Exception e)
{
}
答案 0 :(得分:1)
答案在于问题:
从主方法传递变量的错误
您的main方法不会将任何内容传递给JFrame构造函数。相反,构造函数创建一个新的TCP客户端并再次启动它。构造函数应定义为
public NewJFrame(TCPClient tcpClient) {
...
主方法应该将已经创建并启动的TCPClient传递给构造函数。
答案 1 :(得分:1)
由于您在actionPerformed
方法中关闭套接字连接,我建议也在那里打开连接。
推理: