I'm programming a client server app. I'm wondering to end the connection, which side should decide to end it, client or server?
Then if for example the client did it, should the server still keep open or not?
Suppose we have the below codes for each client and server:
socket = new Socket("127.0.0.1",3000);
........
socket.close();
or
serverSocket = new ServerSocket(3000);
socket = serverSocket.accept();
......
serverSocket.close();
EDIT: according to the matt's answer, i pot my code here and let see why my code doesnt work:
generally, i have a Jframe program as client which will connect to a server and while its open, i want the connection being alive, since it send info to the server and server should response for the result. but if i dont use closing the socket from server it gives an error and if i use, after once calculation, it closes the connection:
Server
private static PrintWriter toClient;
private static BufferedReader fromClient;
public static void run() throws IOException, SAXNotRecognizedException, SAXNotSupportedException, ParserConfigurationException, SAXException, XPathExpressionException
{
System.out.println("Server is waiting for connections...");
while(true)
{
openStreams();
processClient();
closeStreams();
}
}
OpenStream:
public static void openStreams() throws IOException, SAXNotRecognizedException, SAXNotSupportedException, ParserConfigurationException, SAXException, XPathExpressionException
{
serverSocket = new ServerSocket(3000);
socket = serverSocket.accept();
System.out.println("Connected");
toClient = new PrintWriter(socket.getOutputStream(),true);
fromClient = new BufferedReader(new InputStreamReader(socket.getInputStream()));
}
Closestearms:
public static void closeStreams() throws IOException
{
fromClient.close();
toClient.close();
socket.close();
serverSocket.close();
System.out.println("Disconnected");
}
the error i receive if i remove the closestream();
at java.net.PlainSocketImpl.bind(PlainSocketImpl.java:359)
at java.net.ServerSocket.bind(ServerSocket.java:319)
at java.net.ServerSocket.<init>(ServerSocket.java:185)
at java.net.ServerSocket.<init>(ServerSocket.java:97)