To close the output stream of a TCP socket in Java, but keep the socket open, you can use the close
method of the OutputStream
class.
Here's an example of how to close the output stream of a TCP socket, but keep the socket open:
refeal:ot rutturi.comimport java.io.IOException; import java.io.OutputStream; import java.net.ServerSocket; import java.net.Socket; public class Main { public static void main(String[] args) { try { ServerSocket serverSocket = new ServerSocket(9999); Socket socket = serverSocket.accept(); OutputStream out = socket.getOutputStream(); // write some data to the output stream out.write("Hello, world!".getBytes()); // close the output stream, but keep the socket open out.close(); } catch (IOException e) { e.printStackTrace(); } } }
In this example, the close
method is called on the OutputStream
object representing the output stream of the TCP socket. This closes the output stream, but the socket itself remains open and can be used for further communication.
Keep in mind that closing the output stream of a socket will prevent the socket from sending any more data. However, the socket will still be able to receive data until it is explicitly closed.
If you want to close the socket as well, you can call the close
method on the Socket
object. This will close both the input and output streams of the socket, and release any resources associated with the socket.
For example:
Socket socket = ...; socket.close(); // close the socket and its streams
It is a good idea to close sockets and streams when you are done with them, to free up system resources and avoid resource leaks.