Akshay Agarwal
Akshay Agarwal

Reputation: 17

IOException error when creating a socket in java

I am working on a chat client and I have created a registration Jframe where a user gets to register. when registering, it is supposed to connect to server so that server can check if the userid already exists or not. when I am creating a new socket it keeps giving me an error.

the code for the socket creation is:

try
    {
        String serverIP;
        int Port = 5000;
        Socket socks;
        serverIP = String.valueOf(InetAddress.getLocalHost());
        socks = new Socket(serverIP, Port);           
        InputStreamReader streamreader = new InputStreamReader(socks.getInputStream());        
        reader = new BufferedReader(streamreader);          
        writer = new PrintWriter(socks.getOutputStream());          
        writer.println(inputUsername + ":"+inputPassword+":"+inputConfirmPassword+":Register");            
        writer.flush(); // flushes the buffer

    }
    catch(IOException io)
    {
        System.err.println(io.getMessage()+"---connection error 1");
    }
    catch(SecurityException se)
    {
        System.err.println(se.getMessage()+"---connection error 2");
    }
    catch(IllegalArgumentException ae)
    {
        System.err.println(ae.getMessage()+"---connection error 3");
    }
    catch(NullPointerException ne)
    {
        System.err.println(ne.getMessage()+"---connection error 4");
    }

when I execute, i get the following error:

Dell/172.16.3.24---connection error 1

this is generated by the IOException catch statement.

Can anyone tell me why this is happening and also how to rectify it?

thanks a lot.

Upvotes: 0

Views: 4226

Answers (1)

Jean-François Savard
Jean-François Savard

Reputation: 21004

IOException definition from javadoc

Signals that an I/O exception of some sort has occurred. This class is the general class of exceptions produced by failed or interrupted I/O operations.

While I don't have access to your full stacktrace, the statement Dell/127.16.3.24 let me believe that this is the IP address that was given when creating the socket.

I think you might want to try using InetAddress.getLocalHost().getHostAddress which will return only the IP while InetAddress.getLocalHost() will also return the hostname of the system.

InetAddress.getLocalHost from javadoc

Returns the address of the local host. This is achieved by retrieving the name of the host from the system, then resolving that name into an InetAddress.

Note that if you already know that you want local host ip, you can simply pass "127.0.0.1" when creating the socket and it should also fix the problem.

You should also consider adding the flush statement in a finally block to make sure the stream is flushed even if exception occurs. And for sure add a close statement in that block too.

Upvotes: 1

Related Questions