Search code examples
javasocketsinputoutputirc

Java read and write to standard streams not working


code:

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) {}
            }
    }
}

I can send input, but I can not get any output on my screen. Any ideas?


Solution

  • It may be one of the problems. I believe you are not creating the thread as you are calling run method and not start method on your threaded class object:

        t.run();
    

    you should call :

            t.start();
    

    to actually create a thread, as calling run method will simply run the method in a sequential way.