gpt4 book ai didi

Java Socket 连接后关闭?

转载 作者:行者123 更新时间:2023-12-01 19:06:05 26 4
gpt4 key购买 nike

为什么在客户端建立连接后此端口/套接字会关闭?

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



}


}

最佳答案

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

关于Java Socket 连接后关闭?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10069281/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com