3

我正在尝试编写一个程序来侦听它正在运行的机器上的端口 4444 并记录所有传入数据。

到目前为止,这是我的代码。

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;
}
}

当我运行它时,我得到它作为输出。

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

每次它尝试创建输入流时都会挂起。我已经用超级终端对其进行了测试,服务器正在输出消息并且可以连接到端口 4444。我正在运行 java 1.5.0_15 并且无法更新。

谁能看到我做错了什么?

4

2 回答 2

2

您正在使用 BufferedReader 读取行。服务器是否在每条消息的末尾写换行符?

于 2012-10-25T12:38:45.763 回答
0

我发现问题是范围。缓冲的阅读器在函数中被初始化得很好,但一旦回到主中,它就为空。

于 2012-11-07T12:00:53.533 回答