[Okta Webinar] Learn how to a build a cloud-first strategyRegister Now

x
?
Solved

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

Posted on 2005-04-12
13
Medium Priority
?
419 Views
Last Modified: 2010-08-05
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
Comment
Question by:Idarhillgaar
  • 5
  • 4
  • 3
  • +1
13 Comments
 
LVL 29

Expert Comment

by:bloodredsun
ID: 13761896
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
 
LVL 29

Accepted Solution

by:
bloodredsun earned 800 total points
ID: 13761911
Should it not be clientSocket.getInetAddress ().getHostName() ?
0
 

Author Comment

by:Idarhillgaar
ID: 13762116
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
Industry Leaders: We Want Your Opinion!

We value your feedback.

Take our survey and automatically be enter to win anyone of the following:
Yeti Cooler, Amazon eGift Card, and Movie eGift Card!

 
LVL 13

Assisted Solution

by:Webstorm
Webstorm earned 600 total points
ID: 13763785
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
 
LVL 13

Expert Comment

by:Webstorm
ID: 13763804
also you need to close the socket properly in the run() method of Client :

data.getOutputStream().close();
data.getInputStream().close();
data.close();
0
 
LVL 13

Expert Comment

by:Webstorm
ID: 13763827
same thing for the server code :

clientSocket.getOutputStream().close();
clientSocket.getInputStream().close();
clientSocket.close();
0
 

Author Comment

by:Idarhillgaar
ID: 13764529
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
 

Author Comment

by:Idarhillgaar
ID: 13765543
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
 
LVL 15

Assisted Solution

by:aozarov
aozarov earned 600 total points
ID: 13768969
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
 
LVL 13

Assisted Solution

by:Webstorm
Webstorm earned 600 total points
ID: 13770274
or if you want to reconnect to the server many times, you have to create a new socket in the while loop.
0
 

Author Comment

by:Idarhillgaar
ID: 13771270
Thanks all :)
0
 
LVL 13

Expert Comment

by:Webstorm
ID: 13771332
:-)
0
 
LVL 29

Expert Comment

by:bloodredsun
ID: 13771680
Glad to help
0

Featured Post

How to Use the Help Bell

Need to boost the visibility of your question for solutions? Use the Experts Exchange Help Bell to confirm priority levels and contact subject-matter experts for question attention.  Check out this how-to article for more information.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

By the end of 1980s, object oriented programming using languages like C++, Simula69 and ObjectPascal gained momentum. It looked like programmers finally found the perfect language. C++ successfully combined the object oriented principles of Simula w…
Introduction This article is the second of three articles that explain why and how the Experts Exchange QA Team does test automation for our web site. This article covers the basic installation and configuration of the test automation tools used by…
Viewers will learn one way to get user input in Java. Introduce the Scanner object: Declare the variable that stores the user input: An example prompting the user for input: Methods you need to invoke in order to properly get  user input:
Viewers will learn about the regular for loop in Java and how to use it. Definition: Break the for loop down into 3 parts: Syntax when using for loops: Example using a for loop:
Suggested Courses
Course of the Month18 days, 19 hours left to enroll

834 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question