The entire Chat Application in its glory!

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

public class Client {

	JTextArea incoming;
	JTextField outgoing;
	JButton sendbutton;

	BufferedReader reader;
	PrintWriter writer;

	Socket sock;

	public void go(){
		JFrame frame = new JFrame("Client");
		JPanel mainpanel = new JPanel();

		incoming = new JTextArea(15,50);
		incoming.setLineWrap(true);
		incoming.setWrapStyleWord(true);
		incoming.setEditable(false);

		JScrollPane qScroller = new JScrollPane(incoming);
		qScroller.setVerticalScrollBarPolicy(ScrollPaneConstants.VERTICAL_SCROLLBAR_ALWAYS);
		qScroller.setHorizontalScrollBarPolicy(ScrollPaneConstants.HORIZONTAL_SCROLLBAR_ALWAYS);

		outgoing = new JTextField(20);
		sendbutton = new JButton("Send");

		sendbutton.addActionListener(new SendButtonListener());

		mainpanel.add(qScroller);
		mainpanel.add(outgoing);
		mainpanel.add(sendbutton);

		setUpNetworking();

		Thread readerThread = new Thread(new IncomingReader());
		readerThread.start();

		frame.getContentPane().add(BorderLayout.CENTER, mainpanel);
		frame.setSize(400, 400);
		frame.setVisible(true);

	}

	public static void main(String[] args){

		Client client = new Client();
		client.go();
	}

	private void setUpNetworking(){

		try{

			sock = new Socket("127.0.0.1", 5000);
			InputStreamReader streamReader = new InputStreamReader(sock.getInputStream());
			reader = new BufferedReader(streamReader);
			writer = new PrintWriter(sock.getOutputStream());
			System.out.println("Networking established!!");

		}catch(IOException e){
			e.printStackTrace();
		}
	}

	public class SendButtonListener implements ActionListener{

		public void actionPerformed(ActionEvent e){
			try{
				writer.println(outgoing.getText());
				writer.flush();
			}catch(Exception ex){
				ex.printStackTrace();
			}

			outgoing.setText("");
			outgoing.requestFocus();
		}
	}

	public class IncomingReader implements Runnable{

		public void run(){
			String message;
			try{
				while((message = reader.readLine()) != null){
					System.out.println("read" + message);
					incoming.append(message + "\n");
					//incoming.setText(message + "\n");
				}
			}catch(Exception e){
				e.printStackTrace();
			}
		}
	}

}

Advertisements
The entire Chat Application in its glory!

A Simple Chat Server in Java using threads Part 1

The Client
———

The client side first. We import the necessary stuff  needed for this program. The java.net.* contains all
the necessary packages for the networking part. The swing and awt packages are for the GUI.

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

public class Client {

The JTextArea will be used to display all the chat proceedings in real time. The objective of this program is to have mutiple clients connect to a server and receive the information passed to them in real time. We make use of threads in this case.

JTextField is used for passing the chat comments.
JButton is ofcourse used for sending the message.

JTextArea incoming;
JTextField outgoing;
JButton sendbutton;

BufferedReader is used to buffer the inputstream from another source.
We use the PrintWriter to print to the socket. It is similar to using the system println function.

BufferedReader reader;
PrintWriter writer;

Sockets
——–
Sockets form the important part of this program. Simply put, it is an IP addreass with a port number. Now, port numbers vary from about 0 to 65535. It should be noted that the port numbers from 0 to 1023 are reserved and should not, unless for a reason, be used. In this example we will be using the port number 5000 to connect to the server.

Socket sock;

The function go()
—————–
This is the first method to be called. This does the following:
1. Sets up a GUI environment like I mentioned in previous posts.
2. Calls the setUpNetworking() function which will be explained later. Basically, it sets up the networking environment.
3. Most importantly, we start the threads, which I will explain.

public void go(){
JFrame frame = new JFrame("Client");
JPanel mainpanel = new JPanel();

incoming = new JTextArea(15,50);
incoming.setLineWrap(true);
incoming.setWrapStyleWord(true);
incoming.setEditable(false);

JScrollPane qScroller = new JScrollPane(incoming);
qScroller.setVerticalScrollBarPolicy(ScrollPaneConstants.VERTICAL_SCROLLBAR_ALWAYS);
qScroller.setHorizontalScrollBarPolicy(ScrollPaneConstants.HORIZONTAL_SCROLLBAR_ALWAYS);

outgoing = new JTextField(20);
sendbutton = new JButton("Send");

sendbutton.addActionListener(new SendButtonListener());

mainpanel.add(qScroller);
mainpanel.add(outgoing);
mainpanel.add(sendbutton);

setUpNetworking();

Now what this  does is set up a mainpanel which is JPanel. On it we add a JTextArea, which itself is added onto a JScrollPane as seen from the code. The different paramenters of this are set accordingly. The JButton is added and ofcourse, the ActionListener() for the button.

Thread readerThread = new Thread(new IncomingReader());
readerThread.start();

This is how a thread is created. Here we pass a new object of the class IncomingReader which implements the Runnable class, which I will explain in a moment.

frame.getContentPane().add(BorderLayout.CENTER, mainpanel);
frame.setSize(400, 400);
frame.setVisible(true);

}

These are just basic frame housekeeping stuff.

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

The program begins here ofcourse. An object of the type client is created and the go() function is called.

private void setUpNetworking(){

try{

sock = new Socket("127.0.0.1", 5000);

This step creates a socket at the address “127.0.0.1” which is the localhost, ie, the same computer. And we select arbitary socket number of 5000. This number is known to the server.

InputStreamReader streamReader = new InputStreamReader(sock.getInputStream());

The InputStreamReader reads the bytes of data coming from the socket inputstream.

reader = new BufferedReader(streamReader);

This is then passed on to the BufferedReader object.

writer = new PrintWriter(sock.getOutputStream());

The PrintWriter object is finally responsible for putting the message onto the output stream.

System.out.println("Networking established!!");

}catch(IOException e){
e.printStackTrace();
}
}

Before I mention about the networking function, I will explain the concept of the try — catch block of code. Now, while running a code block, exceptions are bound to happen. If we know in advance, that a particular error is likely to happen at a place, we can place it in a try block. So what happens is that if any error occurs in this part will be caught by the catch() statement and then the housekeeping stuff inside the catch block executes. The whole idea of this is to make the program stop gracefully in case of an error.
We make the exception object print out the StackTrace in this case.

public class SendButtonListener implements ActionListener{

public void actionPerformed(ActionEvent e){
try{
writer.println(outgoing.getText());
writer.flush();

We push the content typed into the JTextField into the outputstream of the socket using the writer and
clear the buffer after every step.

}catch(Exception ex){
ex.printStackTrace();
}

outgoing.setText("");
outgoing.requestFocus();
}
}

Once you send the message, you clear the JTextField and then give the focus back to the JTextfield so that the user can type in agagin.

This is the ActionListener for the JButton Send.

public class IncomingReader implements Runnable{

public void run(){
String message;
try{
while((message = reader.readLine()) != null){
System.out.println("read" + message);
incoming.append(message + "\n");

}
}catch(Exception e){
  e.printStackTrace();
  }
 }
 }
}

This is an important part of the program. This class is passed into the thread as an object. This class implements the Runnable interface. Now, each time a thread is created, this class is called. For each Client object created, new copies or threads of execution of this same program is spawned from the existing main thread, which is the only case in a sequential program and they run independently of each other till they complete or the mother thread stops.

Here what we do is to read from the BufferedReader as and when it is not empty and then post in onto the console as well as onto the JTextField using the append function.

A Simple Chat Server in Java using threads Part 1