我的Java服务器/客户机程序只会在我运行它的第三次时工作
我对Java编程还不熟悉,甚至对Java网络编程还比较新,所以我相信问题很简单。我的程序基于提交按钮,该按钮将学生ID提交到服务器 在我运行程序的前两次,它将与服务器建立连接,然后一切都将崩溃,它将永远不会交换字符串 但是,每运行三次,它就会工作得很好,并按照设计交换字符串 客户端:我的Java服务器/客户机程序只会在我运行它的第三次时工作,java,networking,server,client,Java,Networking,Server,Client,我对Java编程还不熟悉,甚至对Java网络编程还比较新,所以我相信问题很简单。我的程序基于提交按钮,该按钮将学生ID提交到服务器 在我运行程序的前两次,它将与服务器建立连接,然后一切都将崩溃,它将永远不会交换字符串 但是,每运行三次,它就会工作得很好,并按照设计交换字符串 客户端: String currentButton = e.getActionCommand(); if(currentButton == "submit"){ try{ So
String currentButton = e.getActionCommand();
if(currentButton == "submit"){
try{
Socket server = new Socket("Localhost",1234);
InetAddress address=InetAddress.getLocalHost();
System.out.println("Connected to "+server.getInetAddress());
System.out.println("Connected to "+address);
BufferedReader br = new BufferedReader(new InputStreamReader(server.getInputStream()));
PrintWriter pw = new PrintWriter(server.getOutputStream(), true);
pw.println(student);
while ((student = br.readLine()) != null) {
System.out.println(student);
pw.println("bye");
if (student.equals("bye"))
break;
}
br.close();
pw.close();
server.close();
} catch (IOException ex){
//ignore exception
}
}
服务器
class NETCW1S {
public static void main(String[] args) throws IOException {
String student;
ServerSocket serverSock = null;
InetAddress address=InetAddress.getLocalHost();
try{
serverSock = new ServerSocket(1234);
System.out.println("Waiting for client connection");
} catch (IOException e) {
System.err.println("Could not listen on port: 1234");
System.exit(1);
}
Socket clientSock = null;
try{
clientSock = serverSock.accept();
} catch (IOException e) {
System.err.println("Accept Failed");
System.exit(1);
}
while (true) {
System.out.println("Connected to "+address);
System.out.println("Waiting for client...");
Socket client = serverSock.accept();
System.out.println("Client from "+client.getInetAddress()+" connected.");
Socket fromClientSocket = serverSock.accept();
PrintWriter pw = new PrintWriter(fromClientSocket.getOutputStream(), true);
BufferedReader br = new BufferedReader(new InputStreamReader(fromClientSocket.getInputStream()));
while ((student = br.readLine()) != null) {
System.out.println("The message: " + student);
if (student.equals("bye")) {
pw.println("bye");
break;
} else {
student = "Server returns " + student;
pw.println(student);
}
}
pw.close();
br.close();
fromClientSocket.close();
}
}
非常感谢 服务器在循环中应该只有一个accept()调用。客户机需要在某个时刻进行connect()调用—现在它似乎根本没有与客户机对话。在try子句中执行close是个坏主意!如果之前抛出了异常,您将不会关闭流/连接,这也可能解释您的问题。同样糟糕的是隐藏异常!不要这样做,即使你不期待他们!“一切都将崩溃”到底意味着什么?嗨,尼尔,如果我将关闭移到try之外,程序将不会编译并生成错误“NETCW1.java:70:error:找不到符号br.close();”Jiri,我的小GUI将会冻结,所以我不能再按提交按钮了@如果您使用Java7或更高版本,GeorgeMahon将阅读“使用资源进行尝试”。我猜你是在GUI线程上运行所有这些东西。永远不要那样做。