Question

I have a code which has 2 classes, SocketDemo and ServerSocketDemo, when the client (SocketDemo) tried to connect to the server (ServerSocketDemo), it waits for a few seconds and then throws

java.net.ConnectionException : Connection timed out

At that particular time, Server shows that connection is established but the client has now reset the connection and throws Exception

First tell me, is it possible to connect two different systems on same connection via sockets ?

Please consider this code fragment and help !

Client code

import java.net.*;
import java.io.*;
class SocketDemo
{
    public static void main(String...arga) throws Exception
    {
        Socket          s = null;
        PrintWriter    pw = null;
        BufferedReader br = null;
        System.out.println("Enter a number one digit");
        int i=(System.in.read()-48); // will read only one character
        System.out.println("Input number is "+i);
        try
        {
            s  = new Socket("192.168.1.5",40000);
            System.out.println(s);
            pw = new PrintWriter(s.getOutputStream());
            System.out.println(pw);
            br = new BufferedReader(new InputStreamReader(s.getInputStream()));
            System.out.println(br);
            System.out.println("Connection established, streams created");
        }
        catch(Exception e)
        {
            System.out.println("Exception in Client "+e);
        }
        pw.println(i);
        pw.flush();
        System.out.println("Data sent to server");
        String str = br.readLine();
        System.out.println("The square of "+i+" is "+str);
    }
}

Server Code :

import java.io.*;
import java.net.*;
class ServerSocketDemo
{
    public static void main(String...args)
    {
        ServerSocket ss=null;
        PrintWriter    pw = null;
        BufferedReader br = null;
        int i=0;
        try
        {
            ss = new ServerSocket(40000);
        }
        catch(Exception e)
        {
            System.out.println("Exception in Server while creating connection"+e);
            e.printStackTrace();
        }
        System.out.print("Server is ready");
        while (true)
        {
            System.out.println ("  Waiting for connection....");
            Socket s=null;
            try
            {
                System.out.println("connection "+s+ "\n printwriter "+pw+"\n bufferedreader "+br);
                s = ss.accept();
                System.out.println("Connection established with client");
                pw = new PrintWriter(s.getOutputStream());
                br = new BufferedReader(new InputStreamReader(s.getInputStream()));
                System.out.println("connection "+s+ "\n printwriter "+pw+"\n bufferedreader "+br);
                i = new Integer(br.readLine());
                System.out.println("i is "+i);
            }
            catch(Exception e)
            {
                System.out.println("Exception in Server "+e);
                e.printStackTrace();
            }
            System.out.println("Connection established with "+s);
            i*=i;
            pw.println(i);
            try
            {
                pw.close();
                br.close();
            }
            catch(Exception e)
            {
                System.out.println("Exception while closing streams");
            }
        }
    }
}
Was it helpful?

Solution

I am able to use your sample code without problems. It's likely some local firewall rule is preventing your client from completing its connection to the server. Try running your client and server on the same host, using 'localhost' or '127.0.0.1' in the client connection.

See top answer in Why would a "java.net.ConnectException: Connection timed out" exception occur when URL is up? for more info.

Also, I note you are not setting socket timeouts for connections or reads in your code. Since you are not setting a timeout in your client socket timeout, the default timeout is zero, which is forever, or more likely whatever your OS default socket timeout is. In general, and especially in production code, not setting a socket timeout for connect or read is a bad idea because it will lead to resource consumption problems that will back up your whole system.

Try setting up your client socket with a connection and read timeout, like this:

        //use a SocketAddress so you can set connect timeouts
        InetSocketAddress sockAddress = new InetSocketAddress("127.0.0.1",40000);
        s  = new Socket();
        //set connect timeout to one minute
        s.connect(sockAddress, 60000);
        //set read timeout to one minute
        s.setSoTimeout(60000);            
        System.out.println(s);
        pw = new PrintWriter(s.getOutputStream());
        ...
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top