【发布时间】:2015-07-14 19:03:58
【问题描述】:
我正在尝试客户端/服务器类型的聊天框(使用 GUI)。我不会详细介绍我在程序中使用的多线程,因为我相信这不是问题的一部分(我希望不是),而且会发布大量代码。无论如何,对于我的客户端和我的服务器,我都在 try 块中创建了一个套接字和一些其他流类,并且由于某种原因,套接字在 catch 块之后关闭。 PS 我不会在任何可能提前结束的地方调用 socket.close() 方法
服务器,这是我的一个类的构造函数。它分解为,我的 main 在不同的线程上有实际的服务器内容,(就像我以前的帖子一样)这是一个修复,以便 gui 可以加载和运行服务器内容,而无需等待另一个。无论如何,没有所有细节,这是我的代码
public ChatAppProtocol(Socket sock)
{
super("ChatAppServer");
// this also has a clas var of Socket
this.sock = sock;
try (
PrintWriter output = new PrintWriter(this.sock.getOutputStream(), true);
BufferedReader input = new BufferedReader(new InputStreamReader(this.sock.getInputStream())) ;
)
{
// first stream of a string is the username loging in from client
String name = input.readLine();
// this returns false, so its not closed
System.out.println("closed?: " + this.sock.isClosed());
}
catch (IOException e)
{
e.printStackTrace();
}
// PROBLEM!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
// closed after the catch blocks before methods even ends
// p.s. i also plan on using the socket in another method but can't since it closes
System.out.println("closed?: " +this.sock.isClosed());
}
现在是我的客户
@FXML
private void login()
{
this.name = this.username.getText().trim();
this.portnum = Integer.parseInt(this.port.getText());
this.name = this.username.getText().trim();
this.ipaddr = this.ip.getText().trim();
try (t
Socket socket = new Socket(this.ipaddr, this.portnum);
PrintWriter output = new PrintWriter(socket.getOutputStream(), true);
)
{
this.sock = socket;
output.println(this.name);
// this returns false, not closed
System.out.println("closed?: " +this.sock.isClosed());
}
catch (UnknownHostException e)
{
System.err.println("Problem at ip: " + this.ipaddr);
System.exit(1);
}
// PROBLEM!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
// returns true here, closes before methods end and i cant reuse it
System.out.println("IS IT CLOSED!!!!!! " + this.sock.isClosed());
}
}
那么,为什么这个不同的类、不同的文件、不同的项目套接字在 try-catch 块后关闭?网上找不到答案,搞了一段时间就卡住了。我在服务器端控制台上看到这个后发现了这个问题
java.net.SocketException: Socket is closed
at java.net.Socket.getOutputStream(Socket.java:943)
at chatappserver.ChatAppProtocol.run(ChatAppProtocol.java:62)
【问题讨论】:
-
你看过
try-with-resources是如何工作的吗? -
@biziclop 我有一阵子没有了,我要在网上放一些示例代码,现在正在阅读它,如果尝试导致问题,有什么办法可以解决?跨度>
-
@DavidSchwartz 谢谢你,但我能做些什么来解决这个问题?我的 IDE 不允许我在 try 中分配我的类套接字变量,它只允许我在 try 块中创建变量时这样做
-
@TannerSummers 向我们展示您的 IDE 不允许的代码,并告诉我们它给您带来的错误。
标签: java multithreading sockets