1

私は非常に単純なクライアントプログラムを書きました

import java.net.*;
import java.io.*;

public class GreetingClient
{
   private Socket cSocket;

   public GreetingClient() throws IOException
   {
        String serverName = "127.0.0.1";
        int port = 5063;
        cSocket = new Socket(serverName,port);
   }


   public static void main(String [] args)
   {
      GreetingClient client;
      try
      {
          client = new GreetingClient();
      }
      catch(IOException e)
      {
          e.printStackTrace();
      }

      while (true)
      {
        try
        {
                InputStream inFromServer = client.cSocket.getInputStream();
                DataInputStream in = new DataInputStream(inFromServer);

                System.out.println("Server says " + in.readUTF());
        }
        catch(IOException e)
        {
                e.printStackTrace();
        }
      }
   }
}

このプログラムをコンパイルすると、次のエラーが表示されます

GreetingClient.java:33: error: variable client might not have been initialized
            InputStream inFromServer = client.cSocket.getInputStream();
                                       ^
1 error

このエラーはどういう意味ですか? new Socket() 呼び出しが失敗した場合 (たとえば、開いているソケットが多すぎる場合)、これはコードでそれを使用できないことを意味しますか? このような状況をどのように処理しますか。

4

1 に答える 1

4
try
{
    client = new GreetingClient();  // Sets client OR throws an exception
}
catch(IOException e)
{
    e.printStackTrace();            // If exception print it
                                    // and continue happily with `client` unset 
}

後で使用しています。

// Use `client`, whether set or not.
InputStream inFromServer = client.cSocket.getInputStream();

これを修正するには、client をnull宣言した場所に設定するか (後で使用すると nullref 例外が発生する可能性があります)、例外を出力した後に "やみくもに" 続行しないでください (たとえば、出力して戻る)。

于 2013-07-27T08:37:46.027 に答える