读取端口出现问题,输入流挂起。

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,无法更新。

有人能看出我做错了什么吗?


你能在进程上运行jstack并发布它所卡住的位置吗? - Martin Serrano
我不熟悉jstack,我该如何在程序上运行它? - Skeith
它是JDK的一部分。'jstack [PID]'将转储跟踪信息。或者,如果您在调试器中运行此程序,则可以在那里查看跟踪信息。或者,您可以尝试首先创建输入流(connection.getInputStream()),以查看是否出现了挂起情况。 - Martin Serrano
是 connection.getInputStream() 卡住了,就像你想的那样,你有解决方案吗? - Skeith
请查看以下链接:http://www.tbray.org/ongoing/When/201x/2012/01/17/HttpURLConnection ,如果您用浏览器查看服务器,您会得到任何内容吗?它是否真的正在提供HTTP协议?HttpURLConnection会通过输入流发送HTTP GET请求。 - Martin Serrano
显示剩余3条评论
2个回答

2

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


你是不是想说 BufferedReader? :) - linski
我不明白那有什么关系,程序在inputstreams构造函数中崩溃,它从未读取任何内容。 - Skeith
@Skeith,如果程序崩溃了,请发布堆栈跟踪。 - Martin Serrano
没有堆栈跟踪,它只是在inputstream调用上挂起。 - Skeith

0

我发现问题出在作用域上。缓冲读取器在函数中被初始化得很好,但一旦回到主函数中,它就变成了 null。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接