Mercenary
Mercenary

Reputation: 2176

Data does not get written to printwriter

I am actually trying to create a program :

public void setUpNetwork(){
    try {
            Socket sock = new Socket("localhost", 1101);
            InputStreamReader read = new InputStreamReader(sock.getInputStream());
            buff = new BufferedReader(read);
            write = new PrintWriter(sock.getOutputStream());
            System.out.println("Network Established");
        } catch (UnknownHostException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
        }
}

Here, once the socket connection is established, I'm trying to pass user entered data to the print stream and then printing out the data in the console.

My server class has only this much:

        ServerSocket server = new ServerSocket(1101);
        Socket socket = server.accept();

When I run this (while running, I first run the server and then the ChatSetUp class), nothing gets printed on the console! Is it because the sersock.accept() gives a socket connection which has a different port and the client can't communicate with the server? If so, I need to pass the socket object from server to setUpNetwork() which is in a different class so that I can create an input stream on it. How do I do it?

Edit:

I've modified the whole program a bit more! I'm using Swing to create the GUI wherein when the user enters text in the text field and hits Send, it triggers the listener and that's where I add the text into PrintWriter. The whole code is given below: ....and setUpNetwork() is also part of this class (not included below)

Edit: Included server code in the same program and starting a new thread for server.

public class ChatGraphs {

JTextField field;
JTextArea area;
PrintWriter write;
BufferedReader buff;
Socket sock;

public static void main(String[] args) {
    ChatGraphs grap = new ChatGraphs();
    grap.doIt();
}

private void doIt() {
    JFrame frame = new JFrame();
    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);


    JPanel allPanel = new JPanel();
    allPanel.setLayout(new BoxLayout(allPanel, BoxLayout.Y_AXIS));

    JPanel areaPanel = new JPanel();
    areaPanel.setLayout(new FlowLayout());
    JLabel alabel = new JLabel("Chats");
    area = new JTextArea(20, 50);
    area.setEditable(false);
    areaPanel.add(alabel);
    areaPanel.add(area);

    JPanel textPanel = new JPanel();
    textPanel.setLayout(new FlowLayout());
    JLabel flabel = new JLabel("Enter");
    field = new JTextField(20);
    JButton button = new JButton("Send");
    button.addActionListener(new ButtonListen());
    textPanel.add(flabel);
    textPanel.add(field);
    textPanel.add(button);

    allPanel.add(areaPanel);
    allPanel.add(textPanel);

    ConnectServer con = new ConnectServer();
    Thread t = new Thread(con);
    t.start();

    AddData add = new AddData();
    Thread t1 = new Thread(add);
    t1.start();

    //setUpServer();
    setUpClient();

    frame.setSize(700,500);
    frame.setVisible(true);
    frame.getContentPane().add(allPanel);
}

public class ButtonListen implements ActionListener{

    @Override
    public void actionPerformed(ActionEvent arg0) {     
        write.println(field.getText());
        write.flush();
        field.setText("");
        field.setRequestFocusEnabled(true);

    }
}

private void setUpClient(){
    try {
        sock = new Socket("localhost", 1101);
        InputStreamReader read = new InputStreamReader(sock.getInputStream());
        buff = new BufferedReader(read);
        System.out.println("Network Established");
    } catch (UnknownHostException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    }
}

public class AddData implements Runnable{

    @Override
    public void run() {
        String line="";
        try {
            while((line=buff.readLine())!=null){
                System.out.println("Another net");
                area.append(line);
            }
            buff.close();
            write.close();
            sock.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

public class ConnectServer implements Runnable{

    public void run() {
        ServerSocket sersock = null;
        Socket sock = null;
        try {
                sersock = new ServerSocket(1101);
                sock = sersock.accept();
                write = new PrintWriter(sock.getOutputStream());
                sersock.close();
                sock.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
    }

}

The exception I get is :

Exception in thread "Thread-2" java.lang.NullPointerException
    at org.sockets.ChatGraphs$AddData.run(ChatGraphs.java:120) // This line is : while((line=buff.readLine())!=null)
    at java.lang.Thread.run(Unknown Source)
Network Established

Upvotes: 3

Views: 820

Answers (2)

jboi
jboi

Reputation: 11912

How do client and server find each other over Sockets?

  • The Client needs to know the network address (IP-Address) of the Server and the port number, the server is listening on.
  • The Server just needs to know which Port it is listening. If it has more network interfaces with different IP-Addresses you can optionally constrain Servers listening to one of the network interfaces (one IP-Address)

So the code snippet to connect a client to the server is like:

Socket socket4Client = new Socket("IP-Address, e.g. 123.45.67.89", PORT_NUMBER);

And the code snippet for the server looks like:

ServerSocket serverSocket = new ServerSocket(PORT_NUMBER);
Socket socket4Server = serverSocket.accept(); // Waits for a Client to connect

For the server side, you most probably want to start a new Thread for each incoming connection. Check these Tiny Applications for some very simple (just not oversimplified) examples.

EDIT/Addition:

About the new issue NullPointerException in the line while(...

You get the exception because buff is null. And this happens because the Thread ConnectServer is started before the method setUpClient() is called. You can create the Thread but must call setUpClient() before you actually start() the thread.

Upvotes: 3

Aaron Digulla
Aaron Digulla

Reputation: 328790

PrintWriter is one of those classes which don't behave well when it comes to buffering and flushing. An easy fix is to use

new PrintWriter(sock.getOutputStream(), true);

to enable auto-flush.

Or you can call write.flush() every time data should be sent to the client.

Note that you need to call flush() once before closing the PrintWriter because it doesn't do that itself (unlike any other I/O class).

Upvotes: 4

Related Questions