Java读取和写入标准流不起作用

时间:2013-08-13 16:13:02

标签: java sockets input output irc

代码:

elaur@colossus[~]$ cat irc.java
import java.net.*;
import java.io.*;

class irc
{
    static Socket server;
    static BufferedReader in;
    static BufferedReader stdin;
    static PrintWriter out;

    public static void main(String args[])
    {
            String user_line;
            try
            {
                    server = new Socket(args[0], 6667);
                    in = new BufferedReader( newInputStreamReader(server.getInputStream()) );
                    stdin = new BufferedReader( newInputStreamReader(System.in) );
                    out = new PrintWriter(server.getOutputStream());
            }
            catch (UnknownHostException e) {}
            catch (IOException e) {}
            irc_in input = new irc_in(server, out, stdin);
            Thread t = new Thread(input);
            t.run();
            while (true)
            {
                    try {
                            System.out.println(in.readLine());
                            System.out.flush();
                            Thread.sleep(2000);
                    } catch (IOException e) {}
                      catch (InterruptedException e) {}
            }
    }
}

class irc_in implements Runnable
{
    static Socket server;
    static PrintWriter out;
    static BufferedReader stdin;

    irc_in(Socket a, PrintWriter b, BufferedReader c)
    {
            server = a;
            out = b;
            stdin = c;
    }

    public void run()
    {
            String user_line;
            while (true)
            {
                    try
                    {
                            Thread.sleep(1000);
                            user_line = stdin.readLine();
                            System.out.println("Got: " + user_line);
                            out.println(user_line);
                            out.flush();
                    }
                    catch (IOException e) {}
                    catch (InterruptedException e) {}
            }
    }
}

我可以发送输入,但我的屏幕上无法获得任何输出。有什么想法吗?

2 个答案:

答案 0 :(得分:3)

这可能是其中一个问题。 我相信你没有创建线程,因为你在调用run方法而不是在线程类对象上启动方法:

    t.run();
你应该致电:

        t.start();

实际创建一个线程,因为调用run方法只会以顺序方式运行该方法。

答案 1 :(得分:2)

应该是 t.start()不是t.run()