简体   繁体   中英

Java Socket Closes After Connection?

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



}


}

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.

You need to add a Stream to it that reacts to the client.

try this:

Socket accepted = serverSocketPort.accept();
InputStream inStr = accepted.getInputStream();

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?

@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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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