0

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



}


}
4

4 回答 4

4

未经测试,但我很确定这是因为您的程序中没有任何其他内容。一旦 ServerSocketPort.accept(); 完成后,程序到达 main 的末尾并关闭。

于 2012-04-09T05:29:59.717 回答
0

该程序运行得非常好。一旦客户端连接或ServerSocket超时,它将立即停止。你在这里的目标是什么?

于 2012-04-09T05:59:14.213 回答
0

您需要向其添加一个响应客户端的 Stream。

尝试这个:

Socket accepted = serverSocketPort.accept();
InputStream inStr = accepted.getInputStream();
于 2012-04-09T05:32:39.097 回答
0

@马修。

恕我直言,乔尔对你的问题有最接近的答案。

“连接已关闭,因为程序在接受连接后存在”

通常,accept 在循环中运行,以便服务器不断监听端口上的连接请求

于 2012-04-09T06:10:43.820 回答