eChat App w/ server 2.0 12-03-2013, 05:43 AM
#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
Server code
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();
}
}
}