0

私の質問は次のとおりです。次のクライアントクラスがあります。

import java.io.IOException;
import java.io.PrintWriter;
import java.net.InetAddress;
import java.net.Socket;
import java.net.UnknownHostException;
import java.util.Scanner;


public class Client {

    public final int portNumber = 6040;
    public Socket socket;
    private PrintWriter pw;
    /**
     * @param args
     * @throws IOException 
     */
    public void connect() throws IOException{


        // du kan vælge at bruge inetadressen til at connecte i socketet.
        InetAddress adr = InetAddress.getByName("localhost");
        socket = new Socket("localhost", portNumber);
        pw = new PrintWriter(socket.getOutputStream());
        pw.println("Connected waiting for input");
        pw.flush();

    }
    /**
     * This method sends the message (that the client(chat person) writes to the user)
     * @param x
     * @throws NullPointerException
     * @throws IOException 
     */
    public void SendChat(String x) throws NullPointerException{
            pw.print(x);
            pw.flush(); 


    }
    public int sendCommando(int id) throws IOException{

         PrintWriter pw = new PrintWriter(socket.getOutputStream());
        pw.print(id);

        /*
         * this part of the program sends a command to the server if the command is 1 then 1 is = Connect.
         * the program then ask the server is the server is full or is it ok to connect? 
         * if the response is not 10 then the program will allow a connection to happen the return type will be the Id of which 
         * the chat person becomes!
         */

        // should the method return 0 the Application will do NOTHING!
        switch (id) {
        case 1:
    int k = reciveCommando();
            if (k== 10) {
                return 10;
            }else if (k<= 3) {
                return k;
            }else {

            return 10;
            }
            /*
             * Closes the connection with the server!
             */
        case 3:

            socket.close();
            return 0;

        default:
            return 0;
        }

    }
    /*
     * this method recives a command from the server! the comands can be found in the ChatCommands.txt
     * returns the command as an integer!
     */
    public int reciveCommando() throws IOException{
        Scanner commandoFromServer = new Scanner(socket.getInputStream());
        Integer i = Integer.parseInt(commandoFromServer.nextLine());
        return i;
    }
    /**
     * Gets a String response from the server. This method i used to create other users and give them the correct username.
     * 
     * @param i
     * @return
     * @throws IOException
     */
    public String getStringResponse(int i) throws IOException {
        pw.print(i);
        pw.flush();
        Scanner commandFromServer = new Scanner(socket.getInputStream());
        String x = commandFromServer.nextLine();
        return x;

    }


}

それ以外には、「メイン」クラスとして使用する GUI があります。

私は SocketTest v3.0.0 というプログラムを持っています (知っている人がいる場合)。基本的には、接続できるサーバーを作成します。

これで私のプログラムが実行され、サーバーに接続されました! しかし、メソッド sendCommand または sendChat またはクライアント プログラム (connect 以外) の他のメソッドを呼び出そうとすると、nullpointer execption が返されます。

問題を絞り込んで、ソケットを宣言するとソケットがnullになるようにしましたが、どうすればこれを修正できますか? Public クラスでソケットを初期化できないためです。

私の言いたいことを理解していただければ幸いです。そうでない場合は、返信して詳細を確認してください。

前もって感謝します!

4

3 に答える 3

1

ソケットの寿命の間、同じストリーム、スキャナーなどを使用する必要があります。I/Oを実行するたびに新しいものを作成する必要はありません。そうしないと、バッファ内のデータが失われます。

于 2012-10-03T23:42:26.640 に答える
1

「sendCommandO」がグローバルなものを使用する代わりに独自のプリントライターを作成するのは奇妙に思えます。2 人のプリントライターが同じストリームにフィードするのは、後で間違いなくトラブルを引き起こします。また、「connect」がすぐに「connected...」を送信するのも奇妙に思えます。

このプログラムのこの構造は、一般に機能しません。なぜなら、あなたの書き込みはブロックされ、読者が何かを読むまでブロックを解除できないからです。少量のデータでは問題なく動作するようです。読み取りと書き込みは別のスレッドで行う必要があります。

これらのどれも差し迫った問題ではありませんが、完全に書き直すことをお勧めします。

于 2012-10-03T22:40:34.137 に答える
0

まず第一に、皆さんの助けと応答のすべてに感謝します。これが私のコードを機能させた理由です。

  1. コードをクリーンアップして、それぞれが1つだけ作成され、クライアントがサーバーに接続したときに作成されたことを確認しました

  2. すべてのメソッドでPrintWriterとScannerの両方を使用できるようにするために、フィールドを静的にする必要がありました

クライアントがサーバーに接続し、メッセージを送受信できるようになりました。ご協力いただきありがとうございます。:)

完全なコードはここにあります:

    import java.io.IOException;
import java.io.PrintWriter;
import java.net.InetAddress;
import java.net.Socket;
import java.util.Scanner;


public class Client {

    public final static int portNumber = 6040;
    public static Socket socket;
    private static PrintWriter pw;
    private static Scanner input;
    /**
     * @param args
     * @throws IOException 
     */
    public static void connect() throws IOException{


        // du kan vælge at bruge inetadressen til at connecte i socketet.
        InetAddress adr = InetAddress.getByName("localhost");
        socket = new Socket("localhost", portNumber);
        input=new Scanner(socket.getInputStream());
        pw = new PrintWriter(socket.getOutputStream());
        pw.println("Connected waiting for input");
        pw.flush();

    }
    /**
     * This method sends the message (that the client(chat person) writes to the user)
     * @param x
     * @throws NullPointerException
     * @throws IOException 
     */
    public void SendChat(String x) throws NullPointerException{
            pw.print(x);
            pw.flush(); 


    }
    public int sendCommando(int id) throws IOException{
        pw.print(id);
        pw.flush();
        /*
         * this part of the program sends a command to the server if the command is 1 then 1 is = Connect.
         * the program then ask the server is the server is full or is it ok to connect? 
         * if the response is not 10 then the program will allow a connection to happen the return type will be the Id of which 
         * the chat person becomes!
         */

        // should the method return 0 the Application will do NOTHING!
        switch (id) {
        case 1:
    int k = reciveCommando();
            if (k== 10) {
                return 10;
            }else if (k < 3) {
                System.out.println("returned k" + k);
                return k;
            }else {

            return 10;
            }
            /*
             * Closes the connection with the server!
             */
        case 3:

            socket.close();
            return 0;

        default:
            return 0;
        }

    }
    /*
     * this method recives a command from the server! the comands can be found in the ChatCommands.txt
     * returns the command as an integer!
     */
    public int reciveCommando() throws IOException{
        Integer i = input.nextInt();
        return i;
    }
    /**
     * Gets a String response from the server. This method i used to create other users and give them the correct username.
     * 
     * @param i
     * @return
     * @throws IOException
     */
    public String getStringResponse(int i) throws IOException {
        pw.print(i);
        pw.flush();
        String x = input.nextLine();
        return x;

    }


}
于 2012-10-04T00:14:42.417 に答える