为什么客户端建立连接后此端口/套接字会关闭?
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);
}
}
}
答案 0 :(得分:4)
未经测试,但我很确定这是因为您的计划中没有其他内容。一旦ServerSocketPort.accept();完成后,程序将结束主程并关闭。
答案 1 :(得分:0)
您需要向其添加一个对客户端做出反应的流。
试试这个:
Socket accepted = serverSocketPort.accept();
InputStream inStr = accepted.getInputStream();
答案 2 :(得分:0)
该程序运行得非常好。一旦客户端连接或 ServerSocket 超时,将停止。你的目标是什么?
答案 3 :(得分:0)
@Matthew。
恕我直言,乔尔最接近你的问题。“连接已关闭,因为程序在接受连接后存在”
通常,accept在循环中运行,以便服务器继续监听端口上的连接请求