Take the 2-minute tour ×
Stack Overflow is a question and answer site for professional and enthusiast programmers. It's 100% free, no registration required.

I’m trying to socket program in Java. Here the client sends a string which should be reversed by the server and sent back to the client. The server is a multithreaded server. Here is the client-side code:

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);
            }
    }
}

Here is the server side code:

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);
            }
    }
}

I get a java.lang.NullPointerException on the server side code when I enter the string and when i try to re-enter the string I get a java.net.SocketException: Socket closed exception.

Client side output:

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 side output:

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

I tried a lot but I don't get from where I get these exceptions. Can anyone help me out here? Thank you in advance! :)

share|improve this question

3 Answers 3

up vote 0 down vote accepted

These 3 lines are the culprits in the client code:

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

Put them outside of the while loop, and in the finally block:

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();
}

The issue is that as it was originally, you closed every resource, but in the next iteration, you wanted to use them agai, without initialising them...

Sidenote

Properly handling exceptions including proper logging of them. Always use either a logging framework like log4j

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

, or the printStackTrace() method

e.printStackTrace();

And don't forget to include the line numbers in your code, if you post a stacktrace....

EDIT

For the reversed issue:

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);
}

What happened? The reversedString just grew and grew with each iteration, without getting erased... This is why I like to declare my variables in just the most strict scope I need them.

EDIT

To make the exit command no tkill the server, this can be one (very simple) solution:

In the ServerConnection class:

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);
    }
}

What is happening here? There is a new "command" stop, which makes the server stop, and the exit just exits the client, but does not stop the server itself...

share|improve this answer
    
That worked! Thanks a lot :). But there's one more problem. When I enter the 1st string as "USA" it prints the reversed string as "ASU". But when I enter a new string, say "Hello", it prints "ASUolleH". But I just want it to print "olleH". How do I do that? –  user2201650 Oct 1 '13 at 20:16
    
@user2201650 I edited my question, the reverse stuff is fixed too –  ppeterka Oct 1 '13 at 20:21
    
It works now! Thank you so much! :) –  user2201650 Oct 1 '13 at 20:26
    
One last question, is my Server code a multithreaded server? I want my Server to be a multithreaded server. Can you help me out here please? –  user2201650 Oct 4 '13 at 18:39
    
@user2201650 Yes, it is a multithreaded server. This line new Thread(sc).start(); creates a new Thread for each connections. –  ppeterka Oct 4 '13 at 18:58

Your server is calling br.readLine(); It will wait until the client sends it, but once you send a String you call:

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

That will release the resource and result in br.readLine() being null

if (line.equals("exit")) { Here line is null, therefore you cannot call equals.

if ("exit".equals(line)) { You can change it like this to prevent that exception here.

Move the close statements to a finally block, even in the server should, if you have an exception in the while, the close are never reached, that may cause memory leaks.

Client:

} finally {
  output.close();
  input.close();
  clientsocket.close();
}

Server:

} finally {
  br.close();
  ps.close();
  clientsocket.close();
}

Note: you can validate them before closing to ensure they are not null.

You may have to provide a case for the input being null anyway, either exit the loop, usually you would use something like this: if (null==line || "exit".equals(line)) {

If the client sends a null, something is wrong.

share|improve this answer

in the 1st run of the loop you are closing all the connections which is causing the issue. output.close(); input.close(); clientsocket.close();,move it down

share|improve this answer

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.