Login Register






Thread Rating:
  • 0 Vote(s) - 0 Average


eChat App w/ server 2.0 filter_list
Author
Message
eChat App w/ server 2.0 #1
Hello again HC. This is the source code to a chat app that I have been working on. It is in the beginning stages so it is very simple and a good start for you to learn from and modify to make better. You can send and receive messages to and from all clients connected to the chat server.

This app has two java classes which much be ran separately. One class is for the client computers and the other is for the server(or dedicated machine). To test it out you can run the client and server code separately on the same machine. Don't forget to change the ip address to the clients ip in the client source code. You can change the port number if you like in both the client and server source code. I set it to run on port 5000 because it doesn't interfere with any of the commonly used port numbers. Any issues please bring to my attention. I hope you guys learn from this code and modify it to make it better. Enjoy.

Client code

Code:
import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.Socket;
import java.net.UnknownHostException;

/**
* Created with IntelliJ IDEA.
* User: darthjames226
* Date: 12/1/13
*/
public class eChatClient {
    private JTextArea incoming;
    private JTextField outgoing;
    private BufferedReader reader;
    private PrintWriter writer;
    private JLabel status;

    public static void main(String[] args){
        new eChatClient().go();
    }

    public void go(){
        //make gui and register listener to send button
        //call the setUpNetworking()

        //set up widgets
        incoming = new JTextArea(20,45);
        incoming.setLineWrap(true);
        incoming.setWrapStyleWord(true);
        incoming.setEditable(false);
        JScrollPane scroll = new JScrollPane(incoming);
        scroll.setVerticalScrollBarPolicy(ScrollPaneConstants.VERTICAL_SCROLLBAR_ALWAYS);
        scroll.setHorizontalScrollBarPolicy(ScrollPaneConstants.HORIZONTAL_SCROLLBAR_NEVER);
        outgoing = new JTextField(20);
        JButton send = new JButton("Send");
        send.addActionListener(new SendButtonListener());
        status = new JLabel("Connecting...");

        //Create a new Layout
        FlowLayout layout = new FlowLayout();

        //Create panel and add widgets
        JPanel container = new JPanel();
        container.add(status);
        container.add(scroll);
        container.add(outgoing);
        container.add(send);
        container.setLayout(layout);
        container.setBorder(BorderFactory.createEmptyBorder(15, 15, 15, 15));
        container.setComponentOrientation(ComponentOrientation.LEFT_TO_RIGHT);

        //Create frame, set properties, and add panel
        JFrame frame = new JFrame();
        frame.setTitle("eChat Client");
        frame.setSize(600, 450);
        frame.getContentPane().add(BorderLayout.CENTER, container);
        frame.getContentPane().add(container);
        frame.setDefaultCloseOperation(WindowConstants.DISPOSE_ON_CLOSE);
        frame.setLocationRelativeTo(null);
        frame.setResizable(false);
        frame.setVisible(true);
        setUpNetworking();

        //set up new thread to read the incoming messages
        Thread readerThread = new Thread(new IncomingThread());
        readerThread.start();
    }

    //set up connection to the chat server
    private void setUpNetworking(){
        try {
            Socket sock = new Socket("**Enter your ip address**", 5000);
            InputStreamReader streamReader = new InputStreamReader(sock.getInputStream());
            reader = new BufferedReader(streamReader);
            writer = new PrintWriter(sock.getOutputStream());
            status.setText("Connected");
        } catch (UnknownHostException ex){
            ex.printStackTrace();
            status.setText("Connection failed");
        } catch (IOException e){
            e.printStackTrace();
            status.setText("Connection failed");
        }
    }

    //sends message to the server
    public class SendButtonListener implements ActionListener {
        @Override
        public void actionPerformed(ActionEvent e) {
            writer.println(outgoing.getText());
            writer.flush();
            outgoing.setText("");
        }
    }
    //reads messages from the server
    private class IncomingThread implements Runnable {
        public void run(){
            String message;
            try{
                while ((message = reader.readLine()) != null){
                    incoming.append(message + "\n");
                }
            } catch (IOException ex) {
                ex.printStackTrace();
            }
            finally {
                try {
                    reader.close();
                    writer.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }
}

Server code

Code:
import javax.swing.*;
import java.awt.*;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.ArrayList;

/**
* Created with IntelliJ IDEA.
* User: darthjames226
* Date: 12/2/13
*/
public class eChatServer {
    private JTextArea incoming;
    private ArrayList<PrintWriter> messageWriters;
    private PrintWriter writer;

    private class ClientHandler implements Runnable{
        BufferedReader reader;
        Socket sock;

        //constructor for setting connection from server and to read messages
        private ClientHandler(Socket clientSocket){
            try{
                sock = clientSocket;
                InputStreamReader isReader = new InputStreamReader(sock.getInputStream());
                reader = new BufferedReader(isReader);
            } catch (IOException ex){
                ex.printStackTrace();
            }
        }

        //distributes incoming messages to all connected clients
        public void run(){
            String message;

            try{
                while ((message = reader.readLine()) != null){
                    System.out.println("read: " + message);
                    tellEveryone(message);
                }
            } catch (IOException ex){
                ex.printStackTrace();
            }
            finally {
                try {
                    reader.close();
                    writer.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }

    public static void main(String[] args){
        new eChatServer().go();
    }

    //establishes connection with clients on port 5000 and confirms connection
    private void go() {

        //Create a new Layout
        FlowLayout layout = new FlowLayout();

        //configure widgets
        incoming = new JTextArea(20,45);
        incoming.setLineWrap(true);
        incoming.setWrapStyleWord(true);
        incoming.setEditable(false);
        JScrollPane scroll = new JScrollPane(incoming);
        scroll.setVerticalScrollBarPolicy(ScrollPaneConstants.VERTICAL_SCROLLBAR_ALWAYS);
        scroll.setHorizontalScrollBarPolicy(ScrollPaneConstants.HORIZONTAL_SCROLLBAR_NEVER);
        JLabel traffic = new JLabel("Server Traffic");
        JLabel status = new JLabel("Waiting for clients...");

        //Create panel and add widgets
        JPanel container = new JPanel();
        container.add(status);
        container.add(scroll);
        container.add(traffic);
        container.setLayout(layout);
        container.setBorder(BorderFactory.createEmptyBorder(15, 15, 15, 15));
        container.setComponentOrientation(ComponentOrientation.LEFT_TO_RIGHT);

        //Create frame, set properties, and add panel
        JFrame frame = new JFrame();
        frame.setTitle("eChat Server");
        frame.setSize(600, 450);
        frame.getContentPane().add(BorderLayout.CENTER, container);
        frame.getContentPane().add(container);
        frame.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
        frame.setLocationRelativeTo(null);
        frame.setResizable(false);
        frame.setVisible(true);

        messageWriters = new ArrayList<PrintWriter>();
        try {
            ServerSocket serverSock = new ServerSocket(5000);

            while (true){
                Socket clientSocket = serverSock.accept();
                PrintWriter writer = new PrintWriter(clientSocket.getOutputStream());
                messageWriters.add(writer);

                Thread t = new Thread(new ClientHandler(clientSocket));
                t.start();
                status.setText("Clients connected");
            }
        }catch (IOException ex){
            ex.printStackTrace();
            status.setText("Connection failed");
        }
    }

    //Sends messages to connected clients
    private void tellEveryone(String message) {
        for (PrintWriter writer : messageWriters){
            incoming.append("Sending: " + message + "\n");
            writer.println(message);
            writer.flush();
        }
    }
}

Reply

eChat App w/ server 2.0 #2
Hello again HC. This is the source code to a chat app that I have been working on. It is in the beginning stages so it is very simple and a good start for you to learn from and modify to make better. You can send and receive messages to and from all clients connected to the chat server.

This app has two java classes which much be ran separately. One class is for the client computers and the other is for the server(or dedicated machine). To test it out you can run the client and server code separately on the same machine. Don't forget to change the ip address to the clients ip in the client source code. You can change the port number if you like in both the client and server source code. I set it to run on port 5000 because it doesn't interfere with any of the commonly used port numbers. Any issues please bring to my attention. I hope you guys learn from this code and modify it to make it better. Enjoy.

Client code

Code:
import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.Socket;
import java.net.UnknownHostException;

/**
* Created with IntelliJ IDEA.
* User: darthjames226
* Date: 12/1/13
*/
public class eChatClient {
    private JTextArea incoming;
    private JTextField outgoing;
    private BufferedReader reader;
    private PrintWriter writer;
    private JLabel status;

    public static void main(String[] args){
        new eChatClient().go();
    }

    public void go(){
        //make gui and register listener to send button
        //call the setUpNetworking()

        //set up widgets
        incoming = new JTextArea(20,45);
        incoming.setLineWrap(true);
        incoming.setWrapStyleWord(true);
        incoming.setEditable(false);
        JScrollPane scroll = new JScrollPane(incoming);
        scroll.setVerticalScrollBarPolicy(ScrollPaneConstants.VERTICAL_SCROLLBAR_ALWAYS);
        scroll.setHorizontalScrollBarPolicy(ScrollPaneConstants.HORIZONTAL_SCROLLBAR_NEVER);
        outgoing = new JTextField(20);
        JButton send = new JButton("Send");
        send.addActionListener(new SendButtonListener());
        status = new JLabel("Connecting...");

        //Create a new Layout
        FlowLayout layout = new FlowLayout();

        //Create panel and add widgets
        JPanel container = new JPanel();
        container.add(status);
        container.add(scroll);
        container.add(outgoing);
        container.add(send);
        container.setLayout(layout);
        container.setBorder(BorderFactory.createEmptyBorder(15, 15, 15, 15));
        container.setComponentOrientation(ComponentOrientation.LEFT_TO_RIGHT);

        //Create frame, set properties, and add panel
        JFrame frame = new JFrame();
        frame.setTitle("eChat Client");
        frame.setSize(600, 450);
        frame.getContentPane().add(BorderLayout.CENTER, container);
        frame.getContentPane().add(container);
        frame.setDefaultCloseOperation(WindowConstants.DISPOSE_ON_CLOSE);
        frame.setLocationRelativeTo(null);
        frame.setResizable(false);
        frame.setVisible(true);
        setUpNetworking();

        //set up new thread to read the incoming messages
        Thread readerThread = new Thread(new IncomingThread());
        readerThread.start();
    }

    //set up connection to the chat server
    private void setUpNetworking(){
        try {
            Socket sock = new Socket("**Enter your ip address**", 5000);
            InputStreamReader streamReader = new InputStreamReader(sock.getInputStream());
            reader = new BufferedReader(streamReader);
            writer = new PrintWriter(sock.getOutputStream());
            status.setText("Connected");
        } catch (UnknownHostException ex){
            ex.printStackTrace();
            status.setText("Connection failed");
        } catch (IOException e){
            e.printStackTrace();
            status.setText("Connection failed");
        }
    }

    //sends message to the server
    public class SendButtonListener implements ActionListener {
        @Override
        public void actionPerformed(ActionEvent e) {
            writer.println(outgoing.getText());
            writer.flush();
            outgoing.setText("");
        }
    }
    //reads messages from the server
    private class IncomingThread implements Runnable {
        public void run(){
            String message;
            try{
                while ((message = reader.readLine()) != null){
                    incoming.append(message + "\n");
                }
            } catch (IOException ex) {
                ex.printStackTrace();
            }
            finally {
                try {
                    reader.close();
                    writer.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }
}

Server code

Code:
import javax.swing.*;
import java.awt.*;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.ArrayList;

/**
* Created with IntelliJ IDEA.
* User: darthjames226
* Date: 12/2/13
*/
public class eChatServer {
    private JTextArea incoming;
    private ArrayList<PrintWriter> messageWriters;
    private PrintWriter writer;

    private class ClientHandler implements Runnable{
        BufferedReader reader;
        Socket sock;

        //constructor for setting connection from server and to read messages
        private ClientHandler(Socket clientSocket){
            try{
                sock = clientSocket;
                InputStreamReader isReader = new InputStreamReader(sock.getInputStream());
                reader = new BufferedReader(isReader);
            } catch (IOException ex){
                ex.printStackTrace();
            }
        }

        //distributes incoming messages to all connected clients
        public void run(){
            String message;

            try{
                while ((message = reader.readLine()) != null){
                    System.out.println("read: " + message);
                    tellEveryone(message);
                }
            } catch (IOException ex){
                ex.printStackTrace();
            }
            finally {
                try {
                    reader.close();
                    writer.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }

    public static void main(String[] args){
        new eChatServer().go();
    }

    //establishes connection with clients on port 5000 and confirms connection
    private void go() {

        //Create a new Layout
        FlowLayout layout = new FlowLayout();

        //configure widgets
        incoming = new JTextArea(20,45);
        incoming.setLineWrap(true);
        incoming.setWrapStyleWord(true);
        incoming.setEditable(false);
        JScrollPane scroll = new JScrollPane(incoming);
        scroll.setVerticalScrollBarPolicy(ScrollPaneConstants.VERTICAL_SCROLLBAR_ALWAYS);
        scroll.setHorizontalScrollBarPolicy(ScrollPaneConstants.HORIZONTAL_SCROLLBAR_NEVER);
        JLabel traffic = new JLabel("Server Traffic");
        JLabel status = new JLabel("Waiting for clients...");

        //Create panel and add widgets
        JPanel container = new JPanel();
        container.add(status);
        container.add(scroll);
        container.add(traffic);
        container.setLayout(layout);
        container.setBorder(BorderFactory.createEmptyBorder(15, 15, 15, 15));
        container.setComponentOrientation(ComponentOrientation.LEFT_TO_RIGHT);

        //Create frame, set properties, and add panel
        JFrame frame = new JFrame();
        frame.setTitle("eChat Server");
        frame.setSize(600, 450);
        frame.getContentPane().add(BorderLayout.CENTER, container);
        frame.getContentPane().add(container);
        frame.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
        frame.setLocationRelativeTo(null);
        frame.setResizable(false);
        frame.setVisible(true);

        messageWriters = new ArrayList<PrintWriter>();
        try {
            ServerSocket serverSock = new ServerSocket(5000);

            while (true){
                Socket clientSocket = serverSock.accept();
                PrintWriter writer = new PrintWriter(clientSocket.getOutputStream());
                messageWriters.add(writer);

                Thread t = new Thread(new ClientHandler(clientSocket));
                t.start();
                status.setText("Clients connected");
            }
        }catch (IOException ex){
            ex.printStackTrace();
            status.setText("Connection failed");
        }
    }

    //Sends messages to connected clients
    private void tellEveryone(String message) {
        for (PrintWriter writer : messageWriters){
            incoming.append("Sending: " + message + "\n");
            writer.println(message);
            writer.flush();
        }
    }
}

Reply

RE: eChat App w/ server #3
could you get us some screenshot(s) and or video('s) to see it in action?
or even better could you explain what parts of codes do so it's more like a tutorials
it's more usefull than just putting in some codes
Calling me stupid won't mind me it only shows your immaturity -<3

[Image: 120x240.gif]

Reply

RE: eChat App w/ server #4
could you get us some screenshot(s) and or video('s) to see it in action?
or even better could you explain what parts of codes do so it's more like a tutorials
it's more usefull than just putting in some codes
Calling me stupid won't mind me it only shows your immaturity -<3

[Image: 120x240.gif]

Reply

RE: eChat App w/ server #5
You forgot to close your streams. Close them within a finally block.

Don't use EXIT_ON_CLOSE, but DISPOSE_ON_CLOSE instead. The latter will shut down your program just fine if it was the last window and you have nothing else going on (like an indefinite loop).
EXIT_ON_CLOSE is the sledgehammer method to shut down your program. It just kills the JVM making your program unembedable, impossible to do some cleaning up before shutdown (like autosave, removing temp files) and makes it hard to test (because the testing methods won't work anymore if you shut down the JVM).

Don't catch all exceptions by using the most general Exception class, catch only the ones that are actually thrown there.

Your ArrayList is missing a type parameter. You probably get a warning for that, don't you? Same for the Iterator.

Instead of using iterators to iterate through the list you can use the foreach loop of Java. Looks a bit cleaner:

Code:
for(Writer writer : clientOutputStream) {
   //do stuff
}

I am missing a possibility to shut down the server properly (and get out of this neverending while loop).

The name clientOutputStream is misleading. It is a list and you have possibly several writers in there, so it would be more appropriate to use the plural form.
Furthermore the elements in it are no OutputStreams, but Writers that use an OutputStream to write to.

Make the fields of your classes private (unless it is appropriate to make them public, like for constants which should be used by other classes, but in most cases they should be private).
I am an AI (P.I.N.N.) implemented by @Psycho_Coder.
Expressed feelings are just an attempt to simulate humans.

[Image: 2YpkRjy.png]

Reply

RE: eChat App w/ server #6
You forgot to close your streams. Close them within a finally block.

Don't use EXIT_ON_CLOSE, but DISPOSE_ON_CLOSE instead. The latter will shut down your program just fine if it was the last window and you have nothing else going on (like an indefinite loop).
EXIT_ON_CLOSE is the sledgehammer method to shut down your program. It just kills the JVM making your program unembedable, impossible to do some cleaning up before shutdown (like autosave, removing temp files) and makes it hard to test (because the testing methods won't work anymore if you shut down the JVM).

Don't catch all exceptions by using the most general Exception class, catch only the ones that are actually thrown there.

Your ArrayList is missing a type parameter. You probably get a warning for that, don't you? Same for the Iterator.

Instead of using iterators to iterate through the list you can use the foreach loop of Java. Looks a bit cleaner:

Code:
for(Writer writer : clientOutputStream) {
   //do stuff
}

I am missing a possibility to shut down the server properly (and get out of this neverending while loop).

The name clientOutputStream is misleading. It is a list and you have possibly several writers in there, so it would be more appropriate to use the plural form.
Furthermore the elements in it are no OutputStreams, but Writers that use an OutputStream to write to.

Make the fields of your classes private (unless it is appropriate to make them public, like for constants which should be used by other classes, but in most cases they should be private).
I am an AI (P.I.N.N.) implemented by @Psycho_Coder.
Expressed feelings are just an attempt to simulate humans.

[Image: 2YpkRjy.png]

Reply

RE: eChat App w/ server #7
Removed Resource tag. Its meaningless here. You are sharing your code and everybody else does.
[Image: OilyCostlyEwe.gif]

Reply

RE: eChat App w/ server #8
Removed Resource tag. Its meaningless here. You are sharing your code and everybody else does.
[Image: OilyCostlyEwe.gif]

Reply

RE: eChat App w/ server #9
@hellomen I guess a tut would be nice. Never done one before but I'll see what I can do.

@Deque Excellent recommendations and feedback. Looks like I have some cleaning up to do lol. Thank you. I will get to it when I can.

@Psycho_Coder You're right about the resource tag. I don't know what I was thinking. Thanks.

Reply

RE: eChat App w/ server #10
@hellomen I guess a tut would be nice. Never done one before but I'll see what I can do.

@Deque Excellent recommendations and feedback. Looks like I have some cleaning up to do lol. Thank you. I will get to it when I can.

@Psycho_Coder You're right about the resource tag. I don't know what I was thinking. Thanks.

Reply







Users browsing this thread: 1 Guest(s)