我正在用Java玩一些游戏,开始用Java代码为基于小型聊天的应用程序制作客户端。我试图使变量ssocket
成为类变量,并且它将是与服务器连接的变量(尚未编写,但这不是问题)。因此,我在类声明的正下方声明了类变量ssocket
,然后(我一直在做并注释掉它)在构造函数中声明ssocket
为空套接字。然后,在一种名为sendToSever
的方法中,我尝试引用它来设置主机,端口和填充物,但是它一直说它应该是局部变量,而不是类变量。但是,稍后在同一方法中的几行中,我引用它很好。另外,当我尝试在ssocket
块中将try
设置为构造函数中的主机和端口时,也没有使用class变量。我想在sendToSever
中正式设置套接字,以便他们每次执行操作时都可以尝试重新连接,但是我不知道如何解决此问题。如果不清楚,我会很乐意编辑这篇文章。
我尝试过:
sendToServer()
里面; 我想将ssocket声明为类变量,然后如果尚未在sendToServer中设置它,则将其设置(这样,如果它无法连接,则该变量仍为null或其他,然后在下次调用时,它会尝试重新连接。)
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JTextField;
import java.awt.Font;
// ...
import java.awt.event.ActionEvent;
public class ClientGUI extends JFrame {
private JTextField lgntxtUsername;
private JPasswordField lgntxtPassword;
private JLabel lgnlblUsername;
private JLabel lgnlblPassword;
private JPanel SignupPanel;
private JLabel lgnlblMAKE;
private JLabel sgnlblImage;
private JLabel sgnlblUsername;
private JTextField sgntxtUsername;
private JLabel sgnlblPassword;
private JPasswordField sgntxtPassword;
private JLabel sgnlblCNFPASS;
private JPasswordField sgntxtPasswordC;
private JButton sgnbtnSIGNUP;
private Socket ssocket;
// I declare the class variable above
public ClientGUI() throws IOException {
// define some JFrame stuff, skipping it
// set to empty socket, though I have tried fully setting it in a try block, hadn't worked
ssocket = new Socket();
// More methods, don't use ssocket at all
public int sendToServer(String text) {
try (
// Says it needs a declaration, doesnt register this as the class variable
socket = new Socket("127.0.0.1", 123456);
// Despite the error in the above line, I reference ssocket fine in the next few lines
PrintWriter out = new PrintWriter(ssocket.getOutputStream(), true);
BufferedReader in = new BufferedReader(new InputStreamReader(ssocket.getInputStream()));) {
out.println(text);
return 200;
} catch (Exception e) {
System.out.println(e.toString());
String[] splitArray = e.toString().split(":");
System.out.println(Arrays.toString(splitArray));
return 500;
}
}
}
答案 0 :(得分:0)
您的错误是您没有关闭构造函数方法:
public ClientGUI() throws IOException {
ssocket = new Socket();
// } should be closed her, but was not
public int sendToServer(String text) {
...
}
答案 1 :(得分:0)
我注意到代码中的几个问题,并进行了以下更改。
下面是修改后的代码。
// static variable, single reference is shared across all instances of the class
private static Socket ssocket = null;
public ClientGUI() throws IOException {
// ssocket is not initialized here
}
public int sendToServer(String text) {
try (
if (ssocket == null) {
// typo, socket is used in code instead of ssocket
ssocket = new Socket("127.0.0.1", 123456);
}
// ...
} catch (Exception e) {
// if connectivity issue occurred, you can close the ssocket and set to null here
// ...
}
}
希望这会有所帮助。