我寫了一個簡單的服務器應用程序,下面給出。 我在run()裏面有一個while循環,但它似乎只執行try塊一次。我希望程序不斷地吐出「GoodBye's」,我怎樣才能做到這一點?while循環只執行一次
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()
{
while(true)
{
try
{
System.out.println("Waiting for client on port " +
serverSocket.getLocalPort() + "...");
Socket server = serverSocket.accept();
System.out.println("Just connected to "
+ server.getRemoteSocketAddress());
DataOutputStream out = new DataOutputStream(server.getOutputStream());
out.writeUTF("\nGoodbye!");
//server.close();
}
catch(SocketTimeoutException s)
{
System.out.println("Socket timed out!");
break;
}
catch(IOException e)
{
e.printStackTrace();
break;
}
continue;
}
}
public static void main(String [] args)
{
try
{
Thread t = new GreetingServer();
t.start();
}
catch(IOException e)
{
e.printStackTrace();
}
}
}
取出
break
聲明從catch塊刪除這些斷裂。 –是你得到例外 –
你可能會得到一些異常,並在捕獲中的循環! – NINCOMPOOP