我已经实现了一个如下所示的服务器。想法是向连接到它的客户端发送“GoodBye”消息。我的问题是我有一个while循环。当它退出while循环时(当我按下^C) 我希望它关闭套接字。我该如何处理这种情况。最后不这样做。
import java.net.*;
import java.io.*;
public class GreetingServer extends Thread
{
private ServerSocket serverSocket;
public GreetingServer() throws IOException
{
serverSocket = new ServerSocket(5063);
serverSocket.setSoTimeout(0);
}
public void run()
{
Socket server = null;
try
{
server = serverSocket.accept();
}
catch(SocketTimeoutException s)
{
System.out.println("Socket timed out!");
}
catch(IOException e)
{
e.printStackTrace();
}
while(true)
{
try
{
System.out.println("Just connected to "
+ server.getRemoteSocketAddress());
DataOutputStream out = new DataOutputStream(server.getOutputStream());
out.writeUTF("\nGoodbye!");
}
catch(SocketTimeoutException s)
{
System.out.println("Socket timed out!");
}
catch(IOException e)
{
e.printStackTrace();
}
finally
{
try
{
server.close();
}
catch (IOException e)
{
e.printStackTrace();
}
}
}
}
public static void main(String [] args)
{
try
{
Thread t = new GreetingServer();
t.start();
}
catch(IOException e)
{
e.printStackTrace();
}
}
}