ePezhman
ePezhman

Reputation: 4010

Server socket always return null to the client , Java

I, doing some computer network homework and I have to develop some sort of distributed DBMS which are connected to each other with peer to peer network, so I have a TCP client and a TCP server in one .java file which running next to each other by threads. the TCP Server of the class always listen to the other TCP client from others and give them service, the problem is when I System.out the String which I have to send back to the client on the Server side it's in the way which it's supposed to be but after sending , the client gets nothing and prints null. I wrote my code based on tutorials I found on the net and I when I test them they worked well but it's not working in my own code. could you see where my problem is? thanks

class CommandComp
{
    int PORT = 1210;
    int PORT2 = 1211;
    String IPLocal = "";
    String IPdest = "";
    InetAddress IPAD;
    InetAddress IPAD2;
    int numOfNodes;
    int numOfNodesnonchanged;
    String[] Nodes;
    Random rand = new Random();
    int max = 2000;
    int min = 1000;
    String command;

    Socket clientSocket;

    CommandComp(String[] IPdest, String IPLocal, int numOfNodes, String command)
    {
        try
        {
            this.numOfNodes = numOfNodes;
            numOfNodesnonchanged = numOfNodes;
            this.IPLocal = IPLocal;
            this.Nodes = IPdest;
            this.command = command;
            // this.IPAD = InetAddress.getByName(this.IPdest);
            this.IPAD2 = InetAddress.getByName(this.IPLocal);
            // clientSocket = new Socket(this.IPAD , PORT ,this.IPAD2 , PORT2 );
        }
        catch (Exception e)
        {
            // //e.printStackTrace();
        }
    }

    public String call()
    {

        int i = 0;
        while (numOfNodes > 0)
        {
            String response = "";
            try
            {
                Thread.sleep(rand.nextInt(max - min + 1) + min);
                i = numOfNodes - 1;
                int max2 = 50;
                int min2 = 10;
                this.IPAD = InetAddress.getByName(Nodes[i]);
                clientSocket = new Socket(this.IPAD, PORT, this.IPAD2, PORT2 + rand.nextInt(max2 - min2 + 1) + min2);
                PrintWriter outToServer = new PrintWriter(clientSocket.getOutputStream(), true);
                BufferedReader inFromServer = new BufferedReader(new InputStreamReader(clientSocket.getInputStream()));
                outToServer.println(command);
                System.out.println(inFromServer.readLine());
                response = inFromServer.readLine();
                outToServer.close();
                inFromServer.close();
                clientSocket.close();
                numOfNodes--;
                System.out.println(Nodes[i] + " Remote DBMS");
                System.out.println(response);

            }
            catch (Exception e)
            {
                e.printStackTrace();
                try
                {
                    clientSocket.close();
                }
                catch (Exception e2)
                {
                    // TODO: handle exception
                }
            }
        }
        return command;
    }
}

class TCPListnerService
    implements Callable<Object>
{    
    String from;

    String to;
    ServerSocket Server;
    String IP = "";
    int numOfNodes;
    int numofNodesUnchanged;
    static clientThread t[];

    TCPListnerService(String IP, int numOfNodes)
    {
        try
        {
            this.IP = IP;
            this.numOfNodes = numOfNodes;
            numofNodesUnchanged = numOfNodes * 2;
            this.t = new clientThread[numofNodesUnchanged];
            InetAddress IPAD = InetAddress.getByName(IP);
            Server = new ServerSocket(1210, 20, IPAD);
        }
        catch (Exception e)
        {
            e.printStackTrace();
        }
    }

    public String call()
        throws Exception
    {

        String gotten = "";
        while (numOfNodes > 0)
        {
            Socket connected = Server.accept();

            for (int i = 0; i < numofNodesUnchanged; i++)
            {
                if (t[i] == null)
                {
                    (t[i] = new clientThread(connected)).start();
                    break;
                }
            }
        }
        return gotten;
    }

}

class clientThread
    extends Thread
{

    Socket clientSocket = null;
    sqlite DB = new sqlite();
    String response = "";
    String fromclient;
    String delims = "[ =)(',\n\t\r]+";
    String[] tokens;

    public clientThread(Socket clientSocket)
    {
        this.clientSocket = clientSocket;
    }

    public void run()
    {

        try
        {
            BufferedReader inFromClient = new BufferedReader(new InputStreamReader(clientSocket.getInputStream()));
            PrintWriter outToClient = new PrintWriter(clientSocket.getOutputStream(), true);
            fromclient = inFromClient.readLine();

            tokens = fromclient.split(delims);
            if (tokens[0].equalsIgnoreCase("create")
                || tokens[0].equalsIgnoreCase("drop")
                || tokens[0].equalsIgnoreCase("delete")
                || tokens[0].equalsIgnoreCase("insert")
                || tokens[0].equalsIgnoreCase("update")
                || tokens[0].equalsIgnoreCase("select"))
            {
                response = DB.RunQuery(fromclient);
                System.out.println(response);
                outToClient.print(response);
                clientS.close();

            }
            else if (tokens[0].equalsIgnoreCase("shut"))
            {
                System.exit(0);
            }

            inFromClient.close();
            outToClient.close();
            clientSocket.close();
        }
        catch (Exception e)
        {
        }
        ;
    }
}

Upvotes: 1

Views: 4891

Answers (1)

user207421
user207421

Reputation: 310957

The problem is here:

inFromClient.close();
outToClient.close();
clientSocket.close();

You are closing (1) the input stream, which closes the socket, (2) the PrintWriter, which flushes it and closes the socket, and (3) the socket. Obviously (2) cannot succeed if the socket is already closed. The data you sent to the client is still buffered, never got flushed, so it never got sent.

Just close the PrintWriter, and close the socket in a finally block in case (2) fails somehow. No need to close the input at all.

Upvotes: 2

Related Questions