![](/img/trans.png)
[英]Java Sockets: My server input stream will not read from the client output stream?
[英]Java sockets - Output stream from server to client via method call
我有这段代码可以让服务器在一个线程中运行。 保持服务器打开的目的是我想通过这个服务器通过 static 方法向客户端发送一些东西。
这是主题:
public class SampleThread extends Thread {
static PrintWriter out;
public void run() {
while(true) {
try(
ServerSocket server = new ServerSocket(SAMPLE_PORT);
Socket socket = server.accept();
){
out = new PrintWriter(socket.getOutputStream());
while(true) {
//nothing, just keeps the server running (is this working?)
}
}catch (IOException e){
//JDialog message that says retrying to connect
}
}
}
}
这是使用服务器向客户端发送内容的 static 方法:
static void sendToClient(String s1, String s2){
out.write(s1 + "\n");
out.write(s2 + "\n");
out.flush();
}
当涉及到通过方法调用从服务器向客户端发送内容的目的时,它就起作用了。 但是,如果我在客户端关闭连接,上面的程序就不能抛出 IOException。 out.write() 方法甚至根本没有抛出任何错误,它只是接受我传递给它的任何内容。
我该怎么做才能使 catch (IOException e) 在客户端关闭连接后仍会被触发?
没关系。 在空的 while(true){} 块中添加套接字输入读取就可以了。
这是我添加的内容:
socket.getInputStream().read();
然后在 catch 块上我添加了一个 out = null:
catch (IOException e){
//JDialog message that says retrying to connect
out = null;
}
之后,我只需要检查 if out:= null,然后再执行 static 方法中的内容:
static void sendToClient(String s1, String s2){
if(out != null) {
out.write(s1 + "\n");
out.write(s2 + "\n");
out.flush();
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.