Skeith
Skeith

Reputation: 2542

Trouble reading from port, InputStream hangs

I am trying to write a program that listens to port 4444 on the machine it is running on and logs all incoming data.

This is my code so far.

import java.io.*;
import java.net.*;

public class Foo {
URL url;
URLConnection connection;
InputStreamReader stream;
BufferedReader in;
String inputLine;
int test = 0;

public Foo()
{
    Connect();
}

public static void main(String[] args)
{
    Foo bridge = new Foo();
    System.out.println("made the class");
    for(;;)
    {
        System.out.println("in the loop");
        try 
        {
            System.out.println("making the try");
            if((bridge.inputLine = bridge.in.readLine()) != null)
            {
                System.out.println("reading the line");
                System.out.println(bridge.inputLine);
            }
        }
        /*catch(NullPointerException n)
        {
            System.out.println(bridge.test);
            bridge.test++;
        }*/
        catch(Exception e)
        {
            System.out.println("MAIN" + e);
        }
    }
}

public int Connect()
{       
    try 
    {
        System.out.println("starting the constructor");
        URL url = new URL("http", "192.168.0.104", 4444, "");
        System.out.println("url ready");
        URLConnection connection = url.openConnection();
        System.out.println("connection ready");
        //connection.setReadTimeout(5000);
        connection.setDoInput(true);
        InputStreamReader stream = new InputStreamReader(connection.getInputStream());
        System.out.println("stream ready");
        BufferedReader in = new BufferedReader(stream);
        //BufferedReader in = new BufferedReader(new InputStreamReader(url.openStream()));
        System.out.println("bufferReader ready");

        return 0;
    }
    catch(Exception e)
    {
        System.out.println("CON" + e);
    }
    return 1;
}
}

When I run it I get this as output.

D:\temp_104\foo>java -cp . foo
starting the constructor
url ready
connection ready

Every single time it hangs when it tries to create an input stream. I have tested it with hyperterminal and the server is outputting messages and can be connected to on port 4444. I am running java 1.5.0_15 and cannot update.

Can anyone see what I am doing wrong ?

Upvotes: 3

Views: 349

Answers (2)

Skeith
Skeith

Reputation: 2542

I found the problem was scope. The buffered reader was being initialised fine in the function but once back in the main it was null.

Upvotes: 0

Martin Serrano
Martin Serrano

Reputation: 3775

You are reading lines with an BufferedReader. Is the server writing newlines at the end of each message?

Upvotes: 2

Related Questions