我正在尝试编写一个简单的TCP服务器,但我遇到的问题是套接字在第一次运行后被关闭(顺便说一下,它在一个线程中运行)。我可以尝试在没有ARM(自动资源管理)的情况下重写它,在try
之后用圆形方块进行重写 - 但我宁愿保留它。
那么,有没有办法在Java中使用ARM编写一个简单的持久性TCP服务器?
public class Server {
/* Server */
public int port = 8088;
public Server (int port){
this.port = port;
System.out.println("Will listen on port " + this.port);
}
public Server () {
System.out.println("Will listen on default port " + port);
}
public void start() {
try (ServerSocket initSocket = new ServerSocket(port);
Socket socket = initSocket.accept();
BufferedReader bfin =
new BufferedReader(new InputStreamReader(socket.getInputStream()));
BufferedOutputStream bfout =
new BufferedOutputStream(socket.getOutputStream())
)
{
String line = bfin.readLine();
while (line != null && !"BYE\n".equals(line)){
String answer = parseadd(line) + "\n";
System.out.println("From client: " + line);
bfout.write(answer.getBytes());
bfout.write("BYE\n".getBytes());
bfout.flush();
line = bfin.readLine();
}
System.out.println("Exiting server while loop!");
}
catch (IOException e) {
System.out.println("Exception caught when trying to");
System.out.println(e.getMessage());
}
}
}