简体   繁体   English

Java sockets - Output stream 通过方法调用从服务器到客户端

[英]Java sockets - Output stream from server to client via method call

I have this code that keeps the server running in a thread.我有这段代码可以让服务器在一个线程中运行。 The purpose of leaving the server open is that I want to send something to the client through this server via a static method.保持服务器打开的目的是我想通过这个服务器通过 static 方法向客户端发送一些东西。

Here's the thread:这是主题:

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
            }
        }
    }
}

Here's the static method that's that uses the server to send something the client:这是使用服务器向客户端发送内容的 static 方法:

static void sendToClient(String s1, String s2){
    out.write(s1 + "\n");
    out.write(s2 + "\n");
    out.flush();
}

When it comes to the purpose of sending something to the client from the server via a method call, it works.当涉及到通过方法调用从服务器向客户端发送内容的目的时,它就起作用了。 However, if I close the connection on the client's side, the program above can't throw the IOException.但是,如果我在客户端关闭连接,上面的程序就不能抛出 IOException。 the out.write() method is not even throwing any error at all, it just accepts whatever I pass to it. out.write() 方法甚至根本没有抛出任何错误,它只是接受我传递给它的任何内容。

What can I do to make it so that the catch (IOException e) will still be triggered once the client closes the connection?我该怎么做才能使 catch (IOException e) 在客户端关闭连接后仍会被触发?

Nevermind.没关系。 Adding a socket input read in the empty while(true){} block did the trick.在空的 while(true){} 块中添加套接字输入读取就可以了。

Here's what I added on it:这是我添加的内容:

socket.getInputStream().read();

Then on the catch block I added an out = null:然后在 catch 块上我添加了一个 out = null:

catch (IOException e){
    //JDialog message that says retrying to connect
    out = null;
}

After that I just need to check if out:= null before executing what's in the static method:之后,我只需要检查 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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM