Studyon Minte9.com
Head First (Java)




Chat



        * Frame & Networking
        * Send & Receive (only one message)
        * Send & Receive (many message)
        * Many clients & many messages

1) Frame ini and Networking between Client & Server
	
	%java 

		// client

		package mychat;

		import java.awt.BorderLayout;
		import javax.swing.*;
		import java.io.*;
		import java.net.*;

		public class ChatClient {
		    
		    JTextArea incomming;
		    JTextField outgoing;

		    public static void main(String[] args) {
			
			ChatClient client = new ChatClient();
			client.setFrameElements();
			client.setUpNetworking();
		    }
		    
		    public void setFrameElements() {
				
			JFrame frame = new JFrame("My Chat");
			JPanel panel = new JPanel();
			
			incomming = new JTextArea(15,50);
			outgoing = new JTextField(20);
			
			JButton sendButton = new JButton("Send");
			
			panel.add(incomming);
			panel.add(outgoing);
			panel.add(sendButton);
			
			frame.getContentPane().add(BorderLayout.CENTER, panel);
			frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
			frame.setSize(400, 500);
			frame.setVisible(true);
			
			incomming.setLineWrap(true);
			incomming.setWrapStyleWord(true);
			incomming.setEditable(false);
			
			JScrollPane scroller = new JScrollPane(incomming);  
			scroller.setVerticalScrollBarPolicy(
						ScrollPaneConstants.VERTICAL_SCROLLBAR_ALWAYS);
			scroller.setHorizontalScrollBarPolicy(
						ScrollPaneConstants.HORIZONTAL_SCROLLBAR_NEVER);
		    }
		    
                    /* --- Look here --- */

		    public void setUpNetworking() {
			try {
			    Socket serverSocket = new Socket("127.0.0.1", 5000);
			    
			    InputStreamReader streamReader = 
						new InputStreamReader(serverSocket.getInputStream());
			    BufferedReader reader = new BufferedReader(streamReader);
			    PrintWriter writer = new PrintWriter(serverSocket.getOutputStream());
			    System.out.println("Networking established with the server");			    
			} catch (Exception e) {
			    e.printStackTrace();
			}
		    }	    
		}

	%java

		// server (on the same terminal, first run the server, then the client)

		package mychat;
		import java.io.*;
		import java.net.*;

		public class ChatServer {
		    
		    public static void main(String[] args) {
			new ChatServer().go();
		    }
		    
                    /* --- Look here --- */

		    public void go() {
			
			try {
			    ServerSocket serverSocket = new ServerSocket(5000);
			    
			    while(true) {
				Socket clientSocket = serverSocket.accept();
				
				PrintWriter writer = new PrintWriter(clientSocket.getOutputStream());
				System.out.println("Got a connection from client");
			    }
			    
			} catch (Exception e) {
			    e.printStackTrace();
			}
		    }
		}


2) Send & Receive only one message from server (not many)
               (use different terminals, othewise it will not work, use same ports)

	%java

                // client (192.168.1.100)

		package mychat;

		import java.awt.BorderLayout;
		import javax.swing.*;
		import java.io.*;
		import java.net.*;
		import java.util.*;
		import java.awt.*;
		import java.awt.event.*;

		public class ChatClient {
		    
		    JTextArea incoming;
		    JTextField outgoing;
		    JButton sendButton;
		    
		    PrintWriter writer;
		    BufferedReader reader;

		    public static void main(String[] args) {
			
			ChatClient client = new ChatClient();
			client.setFrameElements();
			client.setUpNetworking();
			client.setSendAction();
		    }
		    
		    public void setFrameElements() {
				
			JFrame frame = new JFrame("My Chat");
			JPanel panel = new JPanel();
			
			incoming = new JTextArea(15,34);
			outgoing = new JTextField(20);
			
			sendButton = new JButton("Send");
			
			incoming.setLineWrap(true);
			incoming.setWrapStyleWord(true);
			incoming.setEditable(false);
			
			JScrollPane scroller = new JScrollPane(incoming);
			scroller.setVerticalScrollBarPolicy(
                                       ScrollPaneConstants.VERTICAL_SCROLLBAR_ALWAYS);
			scroller.setHorizontalScrollBarPolicy(
                                       ScrollPaneConstants.HORIZONTAL_SCROLLBAR_NEVER);
			
			panel.add(incoming);
			panel.add(outgoing);
			panel.add(sendButton);
			
			frame.getContentPane().add(BorderLayout.CENTER, panel);
			frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
			frame.setSize(400, 500);
			frame.setVisible(true);
		    }
		    
		    public void setUpNetworking() {
			try {
			    Socket serverSocket = new Socket("192.168.1.101", 5000);
			    
			    InputStreamReader streamReader = 
                                            new InputStreamReader(serverSocket.getInputStream());
			    reader = new BufferedReader(streamReader);
			    writer = new PrintWriter(serverSocket.getOutputStream());
				System.out.println("Networking established");
			    
			} catch (Exception e) {
			    e.printStackTrace();
			}
		    }
		    
		    public void setSendAction() {
			sendButton.addActionListener(new SendButtonListener());
		    }
		    
		    public class SendButtonListener implements ActionListener {
			
			@Override
			public void actionPerformed(ActionEvent ev) {
			    String message;
			    try {

                                /* --- Look here --- */

				writer.println(outgoing.getText());
				writer.flush();
				outgoing.setText("");
				outgoing.requestFocus();
				
				message = reader.readLine();
					//System.out.println("Message from server: " + message);
				incoming.append(message + "\n");
			    } catch (Exception ex) {
				ex.printStackTrace();
			    } 
			}
		    } 
		}


	%java

                // server (192.168.1.101)

		package mychat;
		import java.io.*;
		import java.net.*;

		public class ChatServer {
		    
		    public static void main(String[] args) {
			new ChatServer().go();
		    }
		    
		    public void go() {
			String message;
			try {
			    ServerSocket serverSocket = new ServerSocket(5000);
			    
			    while(true) {
				Socket clientSocket = serverSocket.accept();
				
				PrintWriter writer = new PrintWriter(clientSocket.getOutputStream());
				    System.out.println("Got a connection from client");
				    
				InputStreamReader streamReader = 
                                               new InputStreamReader(clientSocket.getInputStream());
				BufferedReader reader = new BufferedReader(streamReader);
			        
                                /* --- Look here --- */

				message = reader.readLine();
				writer.println(message);
				
				 writer.close();
			    }
			    
			} catch (IOException e) {
			    e.printStackTrace();
			}
		    }
		}


3) Send & Receive more than one messages (using threads)

How do you do you do two things at the same time? Where would you put this code? You'd need a loop 
somewhere that was always waiting to read from the server. But where would that go? Once you launch the 
GUI, nothing happens until an event is fired by a GUI component.

We want something to run continuously, checking for messages from the server, but without iruerrupting the 
users ability to interact with the GUI. So while the user is happily typing new messages or scrolling through 
the incoming messages, we want something behind the scene keep reading in new input from the server. 
That means we finally need a new thread. A new, separate Slack.
	
	%java
		
		// client (192.168.1.100)

		package mychat;

		import java.awt.BorderLayout;
		import javax.swing.*;
		import java.io.*;
		import java.net.*;
		import java.util.*;
		import java.awt.*;
		import java.awt.event.*;

		public class ChatClient {
		    
		    JTextArea incoming;
		    JTextField outgoing;
		    JButton sendButton;
		    
		    PrintWriter writer;
		    BufferedReader reader;

		    public static void main(String[] args) {
			
			ChatClient client = new ChatClient();
			client.setFrameElements();
			client.setUpNetworking();
			client.setSendAction();
			client.setThread();
		    }
		    
		    public void setFrameElements() {
				
			JFrame frame = new JFrame("My Chat");
			JPanel panel = new JPanel();
			
			incoming = new JTextArea(15,34);
			outgoing = new JTextField(20);
			
			sendButton = new JButton("Send");
			
			incoming.setLineWrap(true);
			incoming.setWrapStyleWord(true);
			incoming.setEditable(false);
			
			JScrollPane scroller = new JScrollPane(incoming);
			scroller.setVerticalScrollBarPolicy(
                                   ScrollPaneConstants.VERTICAL_SCROLLBAR_ALWAYS);
			scroller.setHorizontalScrollBarPolicy(
                                   ScrollPaneConstants.HORIZONTAL_SCROLLBAR_NEVER);
			
			panel.add(incoming);
			panel.add(outgoing);
			panel.add(sendButton);
			
			frame.getContentPane().add(BorderLayout.CENTER, panel);
			frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
			frame.setSize(400, 500);
			frame.setVisible(true);
		    }
		    
		    public void setUpNetworking() {
			try {
			    Socket serverSocket = new Socket("192.168.1.101", 5000);
			    
			    InputStreamReader streamReader = 
                                              new InputStreamReader(serverSocket.getInputStream());
			    reader = new BufferedReader(streamReader);
			    writer = new PrintWriter(serverSocket.getOutputStream());
				System.out.println("Networking established");
			    
			} catch (Exception e) {
			    e.printStackTrace();
			}
		    }
		    
		    public void setSendAction() {
			sendButton.addActionListener(new SendButtonListener());
			outgoing.addActionListener(new SendButtonListener());
		    }
		    
		    public class SendButtonListener implements ActionListener {
			
			@Override
			public void actionPerformed(ActionEvent ev) {
			    try {
				writer.println(outgoing.getText());
				writer.flush();
			    } catch (Exception ex) {
				ex.printStackTrace();
			    } 
			    outgoing.setText("");
			    outgoing.requestFocus();
			}
		    }
		    
                    /* --- Look here --- */

		    public void setThread() {
			Thread t = new Thread(new IncommingReader());
			t.start();
		    }
		    
		    public class IncommingReader implements Runnable {
			
			@Override
			public void run() {
			    String message;
			    try {
				while ((message = reader.readLine()) != null) {
				   incoming.append(message + "\n");
				}
			    } catch (IOException ex) {
				ex.printStackTrace();
			    } 
			}
		    }

		}


	%java
		
		// server (192.168.1.101)
		
		package mychat;
		import java.io.*;
		import java.net.*;

		public class ChatServer {
		    
		    ServerSocket serverSocket;
		    Socket clientSocket;
		    PrintWriter writer;
			    
		    public static void main(String[] args) {
			new ChatServer().go();
		    }
		    
		    public void go() {
			String message;
			try {
			    serverSocket = new ServerSocket(5000);
			    
			    while(true) {
				clientSocket = serverSocket.accept();
				writer = new PrintWriter(clientSocket.getOutputStream());
		                
                                /* --- Look here --- */

				Thread t = new Thread(new ClientHandler(clientSocket));
				t.start();
				
				System.out.println("Got a connection from client");
			    }
			    
			} catch (IOException e) {
			    e.printStackTrace();
			}
		    }
		    
		    public class ClientHandler implements Runnable {
		
			BufferedReader reader;
		
			public ClientHandler(Socket clientSocket) {
			    try { 
				InputStreamReader streamReader = 
                                            new InputStreamReader(clientSocket.getInputStream());
				reader = new BufferedReader(streamReader);
			    } catch (IOException e) {
				e.printStackTrace();
			    }
			}
		    
			@Override
			public void run() {
			    String message;
			    try {
				writer = new PrintWriter(clientSocket.getOutputStream());
				
				while ((message = reader.readLine()) != null) {
				    System.out.println("message from client: " + message);
				    writer.println(message);
				    writer.flush();
				}
			    } catch(Exception ex) {
				ex.printStackTrace();
			    }
			}
		    }
		}



4) Many clients & many messages


	%java
		// client (compiled and run multiple times on same machine)

		package mychat;

		import java.awt.BorderLayout;
		import javax.swing.*;
		import java.io.*;
		import java.net.*;
		import java.util.*;
		import java.awt.*;
		import java.awt.event.*;

		public class ChatClient {
		    
		    JTextArea incoming;
		    JTextField outgoing;
		    JButton sendButton;
		    
		    PrintWriter writer;
		    BufferedReader reader;
		    
		    String clientName;
		    
		    public static void main(String[] args) {
			
			ChatClient client = new ChatClient();
			client.setFrameElements();
			client.setUpNetworking();
			client.setSendAction();
			client.setThread();
		    }
		    
		    public void setFrameElements() {
				
			JFrame frame = new JFrame("My Chat");
			JPanel panel = new JPanel();
			
			incoming = new JTextArea(15,34);
			outgoing = new JTextField(20);
			
			sendButton = new JButton("Send");
			
			incoming.setLineWrap(true);
			incoming.setWrapStyleWord(true);
			incoming.setEditable(false);
			
			JScrollPane scroller = new JScrollPane(incoming);
			scroller.setVerticalScrollBarPolicy(
                                          ScrollPaneConstants.VERTICAL_SCROLLBAR_ALWAYS);
			scroller.setHorizontalScrollBarPolicy(
                                          ScrollPaneConstants.HORIZONTAL_SCROLLBAR_NEVER);
			
			panel.add(incoming);
			panel.add(outgoing);
			panel.add(sendButton);
			
			frame.getContentPane().add(BorderLayout.CENTER, panel);
			frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
			frame.setSize(400, 500);
			frame.setVisible(true);
		    }
		    
		    public void setUpNetworking() {
			clientName = UUID.randomUUID().toString().substring(0, 5);

			try {
			    Socket serverSocket = new Socket("192.168.1.101", 5000);
			    
			    InputStreamReader streamReader = 
                                         new InputStreamReader(serverSocket.getInputStream());
			    reader = new BufferedReader(streamReader);
			    writer = new PrintWriter(serverSocket.getOutputStream());
				System.out.println("Networking established");
			    
			} catch (Exception e) {
			    e.printStackTrace();
			}
		    }
		    
		    public void setSendAction() {
			sendButton.addActionListener(new SendButtonListener());
			outgoing.addActionListener(new SendButtonListener());
		    }
		    
		    public class SendButtonListener implements ActionListener {
			
			@Override
			public void actionPerformed(ActionEvent ev) {
			    try {
				writer.println(clientName + ": " + outgoing.getText());
				writer.flush();
			    } catch (Exception ex) {
				ex.printStackTrace();
			    } 
			    outgoing.setText("");
			    outgoing.requestFocus();
			}
		    }
		    
		    public void setThread() {
			Thread t = new Thread(new IncommingReader());
			t.start();
		    }
		    
		    public class IncommingReader implements Runnable {
			
			@Override
			public void run() {
			    String message;
			    try {
				while ((message = reader.readLine()) != null) {
				   incoming.append(message + "\n");
				}
			    } catch (IOException ex) {
				ex.printStackTrace();
			    } 
			}
		    }
		    
		    
		}



	%java
	
		// server (use multiple threads & send message to everyone)
		
		package mychat;
		import java.io.*;
		import java.net.*;
		import java.util.*;

		public class ChatServer {
		
		    ArrayList clientOutputStreams = new ArrayList<PrintWriter>();
		    
		    public static void main(String[] args) {
			new ChatServer().go();
		    }
		    
		    public void go() {
			String message;
			try {
			    ServerSocket serverSocket = new ServerSocket(5000);
			    
			    while(true) {
				Socket clientSocket = serverSocket.accept();
				PrintWriter writer = new PrintWriter(clientSocket.getOutputStream());
				
				/* --- Look here --- */
				
				clientOutputStreams.add(writer);
				
				Thread t = new Thread(new ClientHandler(clientSocket));
				t.start();
				
				System.out.println("Got a connection from client");
			    }
			    
			} catch (IOException e) {
			    //e.printStackTrace();
			}
		    }
		    
		    public class ClientHandler implements Runnable {
		
			BufferedReader reader;
		
			public ClientHandler(Socket clientSocket) {
			    try { 
				InputStreamReader streamReader = new InputStreamReader(clientSocket.getInputStream());
				reader = new BufferedReader(streamReader);
			    } catch (IOException e) {
				//e.printStackTrace();
			    }
			}
		    
			@Override
			public void run() {
			    String message;
			    try {
				//writer = new PrintWriter(clientSocket.getOutputStream());
				
				while ((message = reader.readLine()) != null) {
				    System.out.println("message from client: " + message);
				    //writer.println(message);
				    //writer.flush();
				    
				    tellEveryone(message);
				}
			    } catch(Exception ex) {
				//ex.printStackTrace();
			    }
			}
		    }
		    
		    /* --- Look here --- */
		    
		    public void tellEveryone(String message) {
			Iterator i = clientOutputStreams.iterator();
			while(i.hasNext()) {
			    PrintWriter writer = (PrintWriter) i.next();
			    writer.println(message);
			    writer.flush();
			}
		    }
		}