Raggaer
Raggaer

Reputation: 3318

Java server client networking

Should I open - close the connection each time my client GUI sends a message or open a connection one time and keep it open ?

Im sending data using BufferedWriter but this methid just seems to work for one time only, after doing the write and the flush method Im able just to send 1 message to my server, then it just doesnt get the data im sending...

Client connects - sends data to server (1st time) - Works Client sends data again - no data echoed on server console.

Should I open a bufferedwriter each time I want to send data or keep one open all the time and never close it?

My actual code - Client side

Main

public class Main {

    public static void main(String args[]) {

        Client chat = new Client("localhost", 6111);
    }
}

Client

public class Client {

    public Client(String host, int port) {

        SwingUtilities.invokeLater(new Runnable() {

            private Socket chat;

            public void run() {

                try {

                    this.chat = new Socket("localhost", 6113);  

                } catch ( IOException e) {

                    e.printStackTrace();
                }

                Gui gui = new Gui("Chat", this.chat);
            }
        });
    }
}

GUI

public class Gui {

    private JFrame frame;
    private JTextArea area;
    private JTextField field;
    private JMenuBar menu;
    private JButton button;
    private Socket socket;
    private BufferedWriter write;

    public Gui(String title, Socket socket) {

        this.socket = socket;

        try {

            this.write = new BufferedWriter(new OutputStreamWriter(this.socket.getOutputStream()));

        } catch (IOException e) {

            e.printStackTrace();
        }

        this.frame = new JFrame(title);
        this.frame.setSize(new Dimension(400, 400));
        this.frame.setLayout(new BorderLayout());
        this.frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        this.frame.setResizable(false);

        Elements interfce = new Elements(this.frame);

        this.field = interfce.addField("Texto to send...");
        this.menu = interfce.addBar();
        this.area = interfce.addArea();
        this.button = interfce.addButton("Send");
        this.button.addActionListener(new Listener(this.field, this.socket, this.write));
        this.menu.add(this.field);
        this.menu.add(this.button);
        this.frame.setVisible(true);
    }
}

Listener (sends data)

public class Listener implements ActionListener {

    private JTextField text;
    private Socket chat;
    private BufferedWriter writer;

    public Listener(JTextField field, Socket chat, BufferedWriter write) {

        this.text = field;
        this.chat = chat;
        this.writer = write;
    }

    public void actionPerformed(ActionEvent e) {

        System.out.println(this.text.getText());

        try {

            writer.write("Hello\n");
            writer.flush();

        } catch (IOException e1) {

            e1.printStackTrace();
        }
    }
}

And the server

public class Main {

    public static void main(String args[]) {

        Server chat = new Server(6113);
    }
}

public class Server {

    private int port;
    private ServerSocket server;

    public Server(int port) {

        this.port = port;
        startServer();
    }

    public void startServer() {

        try {

            this.server = new ServerSocket(this.port);
            System.out.println("Starting chat server at port " + this.port + "...");

            while (true) {

                Socket s = this.server.accept();
                System.out.println("Client connected - " + s.getLocalAddress().getHostName());
                Thread client = new Thread(new Client(s));
                client.start();
            }

        } catch (IOException e) {

            System.out.println("Error found!");
            e.printStackTrace();
        }
    }
}


public class Client implements Runnable {

    private Socket client;

    public Client(Socket client) {

        this.client = client;
    }

    public void run() {

        try {

            BufferedReader read = new BufferedReader(new InputStreamReader(this.client.getInputStream()));
            System.out.println("Client says - " + read.readLine());

        } catch (IOException e) {

            e.printStackTrace();
        }
    }
}

Upvotes: 0

Views: 111

Answers (2)

Bhaskar
Bhaskar

Reputation: 7523

Should I open - close the connection each time my client GUI sends a message or open a connection one time and keep it open ?

Connection between a Client and Server is generally open for the entire session of messaging and not recreated for sending each message. So keep it open until the client or the Server has to go away.

Look at your Client thread that you start in your server upon accepting a Connection.

public void run() {

    try {

        BufferedReader read = new BufferedReader(new InputStreamReader(this.client.getInputStream()));
        System.out.println("Client says - " + read.readLine());

    } catch (IOException e) {

        e.printStackTrace();
    }
}

Does this give you a hint ? Well - you have to arrange for some sort of looping here within your run() - listening for more inputs from that client.

Upvotes: 1

Braj
Braj

Reputation: 46841

Just do some changes

Server side:

public void run() {

    try {
        BufferedReader read = new BufferedReader(new InputStreamReader(
                this.client.getInputStream()));
        while (true) {
            System.out.println("Client says - " + read.readLine());
        }
    } catch (IOException e) {

        e.printStackTrace();
    }
}

Client side:

use PrintWriter instead of BufferedWriter that provide print new line functionality and auto flush property.

this.write = new PrintWriter(new OutputStreamWriter(this.socket.getOutputStream()),
                true);

 ....

public void actionPerformed(ActionEvent e) {

    System.out.println(this.text.getText());

    try {
        writer.write(this.text.getText());
        writer.println();
    } catch (Exception e1) {
        e1.printStackTrace();
    }
}

Upvotes: 0

Related Questions