简体   繁体   English

Java 连接后套接字关闭?

[英]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();一旦 ServerSocketPort.accept(); finishes, the program hits the end of main and closes.完成后,程序到达 main 的末尾并关闭。

You need to add a Stream to it that reacts to the client.您需要向其添加一个 Stream 以响应客户端。

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.一旦客户端连接或ServerSocket超时,它就会停止。 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通常,accept 是在一个循环中运行的,这样服务器就会一直监听端口上的连接请求

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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