Reputation: 11673
Why does this port/socket close once a connection has been made by a client?
package app;
import java.io.*;
import java.net.*;
public class socketServer {
public static void main(String[] args) {
int port = 3333;
boolean socketBindedToPort = false;
try {
ServerSocket ServerSocketPort = new ServerSocket(port);
System.out.println("SocketServer Set Up on Port: " + port);
socketBindedToPort = true;
if(socketBindedToPort == true) {
Socket clientSocket = null;
try {
clientSocket = ServerSocketPort.accept();//This method blocks until a socket connection has been made to this port.
System.out.println("Waiting for client connection on port:" + port);
/** THE CLIENT HAS MADE A CONNECTION **/
System.out.println("CLIENT IS CONENCTED");
}
catch (IOException e) {
System.out.println("Accept failed: " + port);
System.exit(-1);
}
}
else {
System.out.println("Socket did not bind to the port:" + port);
}
}
catch(IOException e) {
System.out.println("Could not listen on port: " + port);
System.exit(-1);
}
}
}
Upvotes: 0
Views: 436
Reputation: 336
@Matthew.
IMHO, Joel has the closest answer to your question.
"The connection is closed because the program exists after it accepts a connection"
Usually, the accept is run in a loop so that, the server keeps listening to connection requests on the port
Upvotes: 0
Reputation: 2048
The program is running absolutely fine. It will stop as soon as a client connects or the ServerSocket times out. What is your goal here?
Upvotes: 0
Reputation: 9941
You need to add a Stream to it that reacts to the client.
try this:
Socket accepted = serverSocketPort.accept();
InputStream inStr = accepted.getInputStream();
Upvotes: 0
Reputation: 1140
Untested, but I am pretty sure it's because there is nothing else left in your program. Once ServerSocketPort.accept(); finishes, the program hits the end of main and closes.
Upvotes: 4