• Status: Solved
  • Priority: Medium
  • Security: Public
  • Views: 423
  • Last Modified:

I cant identify client IP by getInetAddress when Client is using Threads

Error 1:
its a basic server/client using threads. I can send data from client to Server but I can't seem to retrieve the Client IP.
Error 2:
The client shuts down after connection - catching a conection error.

Client:
public class TCPClient extends Thread
{
      private Socket data = null;
      Thread runner = null;
      private String sentence;
      String serverSentence;
      int val;
////////////////////////////////////////////////////////////////////////////////////      
//Constructor
////////////////////////////////////////////////////////////////////////////////////      
      public TCPClient() throws IOException
      {
            super("Client");
      }
////////////////////////////////////////////////////////////////////////////////////
//Start Client
////////////////////////////////////////////////////////////////////////////////////      
      public synchronized void startClient(String host, int port) throws IOException
    {
        if (runner == null)
        {
            data = new Socket(host,port);
            runner = new Thread(this);
            runner.start();
            System.out.println("Client has made contact with server..");
        }
    }      
////////////////////////////////////////////////////////////////////////////////////
//thread to send data to Server
////////////////////////////////////////////////////////////////////////////////////
      public void run()
      {            
            while(true)
            {                  
                  try
                  {      
                        ObjectOutputStream out = new ObjectOutputStream(data.getOutputStream());
                        out.writeInt(12345);
                        out.close();
                        out.flush();
                  }
                  catch(SocketException se)
                  {
                      System.out.println(se + "Could not connect to server");
                      break;
                  }
                  catch(Exception ex)
                  {
                        System.out.println(ex + "IO ERROR");
                  }                  
            }
    }
 }    

Server:
public class TCPServer implements Runnable
{
    private Thread serverThread = null;
    private ServerSocket listenSocket = null;
    private Socket data = null;
    private boolean done = false;
    private int val;
//////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
//Start server from main
//////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
    public synchronized void startServer(int port) throws IOException
    {
        try
        {
              if (serverThread == null)
              {
                  listenSocket = new ServerSocket(port);
                  serverThread = new Thread(this,"Client Thread");
                  serverThread.start( );
                  System.out.println("Server: Server is running...");
              }
              else
              {
                    serverThread = null;      
                    startServer(port);
              }
        }
        catch(IOException e )
        {
              System.out.println("Cannot create server socket" + e);
        }
    }
//////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
//Stop server from main
//////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
    public synchronized void stopServer( )
    {
        done = true;
        serverThread.interrupt( );
    }
//////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
//returns done
//////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
    protected synchronized boolean getDone( )
    {
        return done;
    }
///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
//Thread communication with Client
//////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
    public void run( )
    {

        if (listenSocket != null)
        {
              System.out.println("Server: Waiting for client requests...");
            while (!getDone( ))
            {
                try
                {
                    Socket clientSocket =  listenSocket.accept( ); //Server socket accept incoming client
                   
                    //ERROR **** Null pointer Exception!!!
                    //String clientID = (data.getInetAddress ().getHostName ()); //String is client ip address
                   
                    System.out.println("Server: A new client has requested connection.");
                   
                    //Read Client data - In this case its an integer.                    
                    ObjectInputStream in = new ObjectInputStream(clientSocket.getInputStream());
                    int i = in.readInt();
                    in.close();
                    System.out.println(i);                  
                        }            
                 
                catch (SocketException e)
                {
                      System.out.println(e + " Connection error");
                      done = true;
                }
                catch (IOException ex)
                {
                      System.out.println(ex + "IO ERROR");
                }              
            }
        }
        else //if serverSocket == null, start 'run' with socket
        {
            run(data);
        }
    }








0
Idarhillgaar
Asked:
Idarhillgaar
  • 5
  • 4
  • 3
  • +1
4 Solutions
 
bloodredsunCommented:
data object is not initialised.

You go stright from private Socket data = null; to data.getInetAddress ().getHostName ().

Are you sure this is what you wanted to do?
0
 
bloodredsunCommented:
Should it not be clientSocket.getInetAddress ().getHostName() ?
0
 
IdarhillgaarAuthor Commented:
Yes a mad typo error from my side - the data port is not initilized you're rigth.

Solved Error 1 :) Good.

About Error 2: I seem to close the connection from server side after the client has delivered its data.
>Is the thread closed? and therefore connection? - what solution should I take to resolve open thread/connection until client disconnects?
>Or is something else happening.

--
Idar
0
Introducing Cloud Class® training courses

Tech changes fast. You can learn faster. That’s why we’re bringing professional training courses to Experts Exchange. With a subscription, you can access all the Cloud Class® courses to expand your education, prep for certifications, and get top-notch instructions.

 
WebstormCommented:
Hi Idarhillgaar,

in the Client code:

>>            runner = new Thread(this);
>>            runner.start();
can be replaced by :
         start();
because Client is already a Thread.

>>                    out.close();
>>                    out.flush();
wrong order. the right one is:
                    out.flush();
                    out.close();

0
 
WebstormCommented:
also you need to close the socket properly in the run() method of Client :

data.getOutputStream().close();
data.getInputStream().close();
data.close();
0
 
WebstormCommented:
same thing for the server code :

clientSocket.getOutputStream().close();
clientSocket.getInputStream().close();
clientSocket.close();
0
 
IdarhillgaarAuthor Commented:
Thanks,

a)If I close the sockets like u propose I get a connection closed error which doesnt happen if I leave them out - this is after I have implemented everything else though.
b)How come client already is a client??

Thanks.
0
 
IdarhillgaarAuthor Commented:
Still get error with or without the close() procedure explained by WebStorm

-Error on Client side - says that Connection is closed after integer has been succesfully sent and received by Server. & server sends back successfully a string.

>Hope anyone can help me with the last error here. Cheers

--
Idar

Heres my new ServerCode

public class TCPServer implements Runnable
{
    private Thread serverThread = null;
    private ServerSocket listenSocket = null;
    private boolean done = false;
//////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
//Start server from main
//////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
    public synchronized void startServer(int port) throws IOException
    {
        try
        {
              if (serverThread == null)
              {
                  listenSocket = new ServerSocket(port);
                  serverThread = new Thread(this,"Client Thread");
                  serverThread.start( );
                  System.out.println("Server: Server is running...");
              }
              else
              {
                    serverThread = null;      
                    startServer(port);
              }
        }
        catch(IOException e )
        {
              System.out.println("Cannot create server socket" + e);
        }
    }
//////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
//Stop server from main
//////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
    public synchronized void stopServer( )
    {
        done = true;
        serverThread.interrupt( );
    }
//////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
//returns done
//////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
    protected synchronized boolean getDone( )
    {
        return done;
    }
///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
//Thread communication with Client
//////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
    public void run( )
    {
             System.out.println("Server: Waiting for client requests...");
        while (!getDone( ))
        {
              try
            {
                  /**********      Accepting Client      ******/                    
                Socket clientSocket =  listenSocket.accept( ); //Server socket accept incoming client
                String clientID = (clientSocket.getInetAddress ().getHostName ()); //String is client ip address                  
                System.out.println("Server: A new client has requested connection."+ clientID);                    
                   
                  /**********      Sends Working collect data from Client      ******/
                  ObjectInputStream in = new ObjectInputStream(clientSocket.getInputStream());
                  int i = in.readInt();
                                                    
                  /**********      Sends confimration from Client      ******/
                  ObjectOutputStream out = new ObjectOutputStream(clientSocket.getOutputStream());
                        out.writeInt(54321);
                        out.flush();                        
                              
                        //Print result of collected items
                        System.out.println("Server: " + i);
                              
                                       
                        //These were taken from output input in order to send an integer.
                        out.close();
                        in.close();      
                  }              
            catch (SocketException e)
            {
                     System.out.println("Server: Connection error " + e);
                     //done = true;
            }
            catch (IOException ex)
            {
                    System.out.println("Server: IO ERROR " + ex);
            }              
          }
      }
}

Heres my new ClientCode

public class TCPClient implements Runnable
{
      private Socket data = null;
      Thread runner = null;
      private String sentence;
      String serverSentence;
////////////////////////////////////////////////////////////////////////////////////      
//Constructor
////////////////////////////////////////////////////////////////////////////////////      
      public TCPClient() throws IOException
      {

      }
////////////////////////////////////////////////////////////////////////////////////
//Start Client
////////////////////////////////////////////////////////////////////////////////////      
      public synchronized void startClient(String host, int port) throws IOException
    {
        if (runner == null)
        {
            data = new Socket(host,port);
            runner = new Thread(this);
            runner.start();            
            System.out.println("Client has made contact with server..");
        }
    }      
////////////////////////////////////////////////////////////////////////////////////
//thread to send data to Server
////////////////////////////////////////////////////////////////////////////////////
      public void run()
      {            
            while(true)
            {                  
                  try
                  {      
                        /**********      Works! - Atempting to send data to Server      ******/
                        ObjectOutputStream out = new ObjectOutputStream(data.getOutputStream());
                        out.writeInt(12345);
                        out.flush(); //Flush sends the text                  
                        
                        /**********      Works! - Atempting to retrieve data from Server      ******/
                        ObjectInputStream in = new ObjectInputStream(data.getInputStream());
                int i = in.readInt();
                System.out.println("Client: " + i);
                        
                        //Closes.
                        in.close();
                        out.close();                        
                  }
                  catch(SocketException se)
                  {
                      System.out.println("Client: Could not connect to server " + se);
                      break;
                  }
                  catch(Exception ex)
                  {
                        System.out.println("Client: IO ERROR " + ex);
                  }                  
          }
      }
}    
0
 
aozarovCommented:
The reason that you get this exception in the client side is because the client logic is inside a while (true) statement.
The first iteration probably goes successfuly but then at the end of that iteration you are closing the input/output streams.
Then, because of the while (true) loop, you are going to try and get the outputstream again and this is where you are probably failing.
the while loop in the server side make scense (in case you want to interact with multiple clients) but is there any reason your client
run logic is trying to run forvever? If not then just remove the loop. If you want the same client and server to keep converse forever then
you will need to to take the logic that creates the streams and close the streams outside of the loop.
0
 
WebstormCommented:
or if you want to reconnect to the server many times, you have to create a new socket in the while loop.
0
 
IdarhillgaarAuthor Commented:
Thanks all :)
0
 
WebstormCommented:
:-)
0
 
bloodredsunCommented:
Glad to help
0
Question has a verified solution.

Are you are experiencing a similar issue? Get a personalized answer when you ask a related question.

Have a better answer? Share it in a comment.

Join & Write a Comment

Featured Post

Cloud Class® Course: Microsoft Office 2010

This course will introduce you to the interfaces and features of Microsoft Office 2010 Word, Excel, PowerPoint, Outlook, and Access. You will learn about the features that are shared between all products in the Office suite, as well as the new features that are product specific.

  • 5
  • 4
  • 3
  • +1
Tackle projects and never again get stuck behind a technical roadblock.
Join Now