Daniel Lopez
Daniel Lopez

Reputation: 1798

Java Socket Method Blocks When 'connect' is called

Before answering, please note that this is a client side issue and not a server issue. Since I used telnet in the terminal, to connect to the server, and telnet was able to connect to the server. Now, I do not know why the connect method cannot connect I used both the localhost address and the private IP address of the server. It just blocks and it never invokes the callback method.

                client.connect(new InetSocketAddress(hostname, 1993));
                callback.onConnection(); // Never invokes!
                OutputStream writer = client.getOutputStream();
                InputStream reader = client.getInputStream();
                byte[] buffer = new byte[1024 * 1024];

P.S Am I doing something wrong. It cannot be firewall issue since telnet was able to connect to the server and I think I do not have a firewall since I am running this code in my Ubuntu machine. Both the server and client are using the TCP protocol and no exception is being thrown neither on the client and server side. Any suggestion to what might be wrong can be very useful. I can show more code like the sever code. The server is written in C++ and the client is written in Java.

Edit:

I finally was able to establish a connection. Instead of using the connect method I interally called connect by using the constructor of the socket. I do not know why connect doesnt' work?

Here is the code modification:

            client = new Socket(hostname, port);
            callback.onConnection();
            OutputStream writer = client.getOutputStream();
            InputStream reader = client.getInputStream();
            byte[] buffer = new byte[1024 * 1024];
            reader.read(buffer);

Upvotes: 0

Views: 1930

Answers (3)

Daniel Lopez
Daniel Lopez

Reputation: 1798

I finally was able to establish a connection. Instead of using the connect method I interally called connect by using the constructor of the socket. I do not know why connect doesnt' work?

Here is the code modification:

        client = new Socket(hostname, port);
        callback.onConnection();
        OutputStream writer = client.getOutputStream();
        InputStream reader = client.getInputStream();
        byte[] buffer = new byte[1024 * 1024];
        reader.read(buffer);

Upvotes: 0

scorpdaddy
scorpdaddy

Reputation: 303

Have you tried checking isUnresolved() on the address before calling connect?

Upvotes: 1

marwinXXII
marwinXXII

Reputation: 1446

I suppose you are using blocking sockets so, connect method will block execution, until connection is established. You can try create nonblocking-sockets using http://docs.oracle.com/javase/1.4.2/docs/api/java/nio/channels/SocketChannel.html for example

Upvotes: 1

Related Questions