2

Javaでプログラムをソケットしようとしています。ここでクライアントは文字列を送信します。この文字列はサーバーによって反転され、クライアントに送り返されます。サーバーはマルチスレッド サーバーです。クライアント側のコードは次のとおりです。

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

class ClientSystem
{
    public static void main(String[] args)
    {
            String hostname = "127.0.0.1";
            int port = 1234;

            Socket clientsocket = null;
            DataOutputStream output =null;
            BufferedReader input = null;

            try
            {
                    clientsocket = new Socket(hostname,port);
                    output = new DataOutputStream(clientsocket.getOutputStream());
                    input = new BufferedReader(new InputStreamReader(clientsocket.getInputStream()));
            }
            catch(Exception e)
            {
                    System.out.println("Error occured"+e);
            }

            try
            {
                    while(true)
                    {
                            System.out.println("Enter input string ('exit' to terminate connection): ");
                            BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
                            String inputstring = br.readLine();
                            output.writeBytes(inputstring+"\n");

                            //int n = Integer.parseInt(inputstring);
                            if(inputstring.equals("exit"))
                                    break;

                            String response = input.readLine();
                            System.out.println("Reversed string is: "+response);

                            output.close();
                            input.close();
                            clientsocket.close();
                    }
            }
            catch(Exception e)
            {
                    System.out.println("Error occured."+e);
            }
    }
}

サーバー側のコードは次のとおりです。

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

public class ServerSystem
{
    ServerSocket server = null;
    Socket clientsocket = null;
    int numOfConnections = 0, port;

    public ServerSystem(int port)
    {
            this.port = port;
    }

    public static void main(String[] args)
    {
            int port = 1234;
            ServerSystem ss = new ServerSystem(port);
            ss.startServer();
    }

    public void startServer()
    {
            try
            {
                    server = new ServerSocket(port);
            }
            catch(Exception e)
            {
                    System.out.println("Error occured."+e);
            }

            System.out.println("Server has started. Ready to accept connections.");

            while(true)
            {
                    try
                    {
                            clientsocket = server.accept();
                            numOfConnections++;
                            ServerConnection sc = new ServerConnection(clientsocket, numOfConnections, this);
                            new Thread(sc).start();
                    }
                    catch(Exception e)
                    {
                            System.out.println("Error occured."+e);
                    }
            }
    }

    public void stopServer()
    {
            System.out.println("Terminating connection");
            System.exit(0);
    }
}

class ServerConnection extends Thread
{
    BufferedReader br;
    PrintStream ps;
    Socket clientsocket;
    int id;
    ServerSystem ss;

    public ServerConnection(Socket clientsocket, int numOfConnections, ServerSystem ss)
    {
            this.clientsocket = clientsocket;
            id = numOfConnections;
            this.ss = ss;

            System.out.println("Connection "+id+" established with "+clientsocket);
            try
            {
                    br = new BufferedReader(new InputStreamReader(clientsocket.getInputStream()));
                    ps = new PrintStream(clientsocket.getOutputStream());
            }
            catch(Exception e)
            {
                    System.out.println("Error occured."+e);
            }
    }

    public void run()
    {
            String line, reversedstring = "";

            try
            {
                    boolean stopserver = false;
                    while(true)
                    {
                            line = br.readLine();
                            System.out.println("Received string: "+line+" from connection "+id);
                            //long n = Long.parseLong(line.trim());

                            if(line.equals("exit"))
                            {
                                    stopserver = true;
                                    break;
                            }
                            else
                            {
                                    int len = line.length();
                                    for (int i=len-1; i>=0; i--)
                                            reversedstring = reversedstring + line.charAt(i);
                                            ps.println(""+reversedstring);
                            }
                    }
                    System.out.println("Connection "+id+" is closed.");
                  br.close();
                    ps.close();
                    clientsocket.close();

                    if(stopserver)
                            ss.stopServer();
            }
            catch(Exception e)
            {
                    System.out.println("Error occured."+e);
            }
    }
}

文字列を入力するとサーバー側のコードで java.lang.NullPointerException が発生し、文字列を再入力しようとすると java.net.SocketException: Socket closed 例外が発生します。

クライアント側の出力:

Enter input string ('exit' to terminate connection): 
usa
Reversed string is: asu
Enter input string ('exit' to terminate connection): 
usa
Error occured.java.net.SocketException: Socket closed

サーバー側の出力:

Server has started. Ready to accept connections.
Connection 1 established with Socket[addr=/127.0.0.1,port=3272,localport=1234]
Received string: usa from connection 1
Received string: null from connection 1
Error occured.java.lang.NullPointerException

私は多くのことを試しましたが、これらの例外がどこから得られるのかわかりません。

4

3 に答える 3

2

これらの 3 行は、クライアントコードの犯人です。

output.close();
input.close();
clientsocket.close();

それらを while ループの外側に置き、finally ブロックに入れます。

try {
    while(true) {
      // client code here
    }
} catch (Exception e) {
     e.printStackTrace(); //  notice this line. Will save you a lot of time!
} finally {
    output.close(); //close resources here!
    input.close();
    clientsocket.close();
}

問題は、元のようにすべてのリソースを閉じましたが、次の反復で、それらを初期化せずに再度使用したかったことです...

サイドノート

例外の適切なロギングを含む、例外の適切な処理。常に次のようなロギング フレームワークを使用します。log4j

LOG.error("Unexpected error when deionizing the flux capacitor",e);

、またはprintStackTrace()メソッド

e.printStackTrace();

また、スタックトレースを投稿する場合は、コードに行番号を含めることを忘れないでください....

編集

逆の問題の場合:

else
{
    int len = line.length();

    reversedString=""; //this line erases the previous content of the reversed string

    for (int i=len-1; i>=0; i--) { //always use brackets!!!
        reversedstring = reversedstring + line.charAt(i);
    }
    ps.println(""+reversedstring);
}

どうしたの?reversedString は、消去されることなく、反復ごとに成長していきました...これが、必要な最も厳密なスコープで変数を宣言するのが好きな理由です。

編集

終了コマンドでサーバーを強制終了しないようにするには、これが (非常に単純な) 解決策の 1 つです。

ServerConnection クラスで:

while(true)
{
    line = br.readLine();
    System.out.println("Received string: "+line+" from connection "+id);

    if(line.equals("exit"))
    {
        break; //just stop this connection, don't kill server
    }
    else if(line.equals("stop"))
    {
        stopserver = true; //stop server too
        break;
    }
    else
    {
        int len = line.length();
        for (int i=len-1; i>=0; i--) {
            reversedstring = reversedstring + line.charAt(i);
        }
        ps.println(""+reversedstring);
    }
}

ここで何が起きてるの?サーバーを停止させる新しい「コマンド」がstopあり、出口はクライアントを終了するだけですが、サーバー自体は停止しません...

于 2013-10-01T20:11:30.533 に答える
0

ループの最初の実行では、問題の原因となっているすべての接続を閉じています。output.close(); 入力.close(); clientsocket.close();、下に移動

于 2013-10-01T20:12:39.680 に答える