October 24, 2014
Hot Topics:
RSS RSS feed Download our iPhone app

Designing a Broadcast Messenger Using Socket Programming in Java

  • February 20, 2004
  • By Fatima Ahmed
  • Send Email »
  • More Articles »

Introduction

Java is a powerful, object-oriented language that supports much functionality, including client/server communication through socket programming, windows-based programming, console programming, database connectivity, image, and sound programming. Java is mainly designed for Internet programming and to create small applications that can be embedded inside an HTML page, known as Applets.

Before coming to the actual coding of the program, some important terms need to be defined so that the concept becomes clear. The purpose of a broadcast messenger is to create a server that is responsible for receiving and responding to messages that are received from the clients to all the clients available on the network. This is called as Broadcasting (to send the packet or message to all the hosts).

The server/client architecture is basically applied here because one of the computers will act as a Server responding to client messages, while all other computers will behave as Clients that only send requests to the server to perform some task. Sockets are logical connections that are created to connect the computers to each other. A port number and a host IP address/host name is required to create a socket.

Multithreading means that many threads of a process can be run on a single processor assigning them an equal time slice and priority, each feeling that it is the only process running. Because here, many clients connect to the same port to the server, multithreading is implemented. Threads are that pieces of a process or program that are assigned some resources, such as file, I/O, and so forth, and are able to run individually.

Java Code Explanation

First of all, we create a server, create the server and client class, and import the following files:

import java.io.*;
import java.net.*;
import java.awt.*;

Design an interface for the server class so that the incoming requests from the clients can be shown on a window form. A simple server window design for this program is as follows:

Figure 1: A view of the server window that shows all the logging in and out, clients' names, and IP addresses.

We create a Menu on the top of the window, a Text Area field in the middle of the window, and a Help dialog box. We set the window's container layout manager to Flow layout. The flow layout manager places components in a row, and when the row is full, it automatically spills the components (Text Boxes, Menu bar, Labels, and the like) to the next row. There are other layout managers available in Java, such as Border layout manager, Grid layout manager, Card layout manager, Box layout manager, and GridBag layout manager. Here is the sample code:

public class ChatServer extends JFrame {
public ChatServer(String title)    //CONSTRUCTOR TO INITIALIZE THE
                                   //ChatServer CLASS
{
output = new TextArea (15,40);     //output IS A TextArea COMPONENT
                                   //OF THE ChatServer CLASS
output.setEditable (false);
output.setFont(f);
output.setForeground(Color.blue);

setTitle(title);         //TO SET THE TITLE OF THE CLIENT WINDOW
setJMenuBar(menuBar);    //TO INITIALIZE THE MENU BAR ON THE WINDOW
JMenu fileMenu = new JMenu("File");
JMenu colorMenu = new JMenu("Color");
JMenu helpMenu = new JMenu("Help");

//Main menu Shortcuts:
fileMenu.setMnemonic('F');
colorMenu.setMnemonic('C');
helpMenu.setMnemonic('H');

//About Dialog init:
aboutItem = new JMenuItem("About");
//aboutItem.addActionListener((ActionListener)this);
helpMenu.add(aboutItem);
addMenuItem(helpMenu,aboutAction = new AboutAction("About"));

//Initialize menu items:
menuBar.add(fileMenu);
menuBar.add(colorMenu);
menuBar.add(helpMenu);

enableEvents(AWTEvent.WINDOW_EVENT_MASK);

class AboutAction extends AbstractAction    //CREATES AN ABSTRACT
                                            //INTERNAL CLASS FOR
                                            //About
{
JOptionPane opt;
String name;
public AboutAction(String Name)

   {
   this.name=Name;
   }

//About menu event:
public void actionPerformed(ActionEvent ae)
   {
//if(ae.getSource() == aboutAction)
      {

      JOptionPane.showMessageDialog
      (opt,"ChitChat_Broadcast_Messenger\nCopyright
      Fatima_Ahmed","About_ChitChat_Broadcast_Messenger",J
      OptionPane.INFORMATION_MESSAGE);
      }

   }
}

Figure 2: About dialog box

public static void main (String args[]) throws IOException {

ChatServer ServerWindow = new ChatServer("ChitChat Broadcast
                                         Messenger: Server Window");
    //CREATES AN OBJECT OF SERVER
Toolkit theKit = ServerWindow.getToolkit();   //TO CREATE AN OBJECT
                                              //OF ToolKit
Dimension wndSize = theKit.getScreenSize();

ServerWindow.setBounds(wndSize.width/4,wndSize.height/4,
                       wndSize.width/2,wndSize.height/2);
ServerWindow.setVisible(true);
ServerWindow.getContentPane().add ("North", output);
    //TO ADD THE TextArea (output) AT THE NORTH OF THE WINDOW
ServerWindow.getContentPane().setLayout(new FlowLayout
                                        (FlowLayout.CENTER));
    //TO SET THE LAYOUT AS CENTRALLY FLOW
ServerWindow.pack();    //TO PACK THE SERVER WINDOW WITH ABOVE
                        //INITIALIZE COMPONENTS

   if (args.length != 1)
      throw new IllegalArgumentException ("Syntax: ChatServer
                                           <port>");
   int port = Integer.parseInt (args[0]);
   String logins;
   ServerSocket server = new ServerSocket (port);
      //TO CREATE AN OBJECT FOR SERVER'S SOCKET
   while (true) {
      Socket client = server.accept ();    //CALLS THE accept()
                                           //METHOD WHENEVER THE
                                           //CLIENTS REQUEST
      System.out.println ("Accepted from " +
                           client.getInetAddress ()+
                           " with name "+logins);
      ChatHandler handler = new ChatHandler (client,yourname);
      handler.start ();    //THE BROADCASTING OF MESSAGES IS
                           //STARTED BY start() METHOD
      output.append ("\n Accepted from " +
                      client.getInetAddress ()+"\n");
   }
}

The sockets are created through another class, "ChatHandler", for the server that is included in the Demo Project file. Now, we design the Client class that looks somewhat like this:

Figure 3: The Client messenger window asks the login name of the user each time the connection is initiated.

Figure 4: A view of the client window having font and color selection boxes along with a menu bar to control the window.

Import the following files in the Client class file. We have created another class, "SketchFrame", that is used for defining the interface of the client window whose object is passed to the client window. Here, we describe the basic functionality of the Socket class in Java and then implementing the methods of start ( ), run ( ), and stop ( ) on the client threads. This class has the following imported files:

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

public class ChatClient implements Runnable, WindowListener, ActionListener, ListSelectionListener { protected String host; protected int port; public TextArea output; protected TextField input; String yourname; SketchFrame window; public ChatClient (String host, int port, SketchFrame window) { //CONSTRUCTOR INITIALIZING THE ChatClient CLASS this.host = host; //host AND port WILL BE USED TO OPEN THE //SOCKET this.port = port; this.yourname=JOptionPane.showInputDialog("Enter Login name:"); //TO CREATE AN INPUT DIALOG BOX window.setSize(100,100); //TO SET THE SIZE OF THE CLIENT //WINDOW window.getContentPane().add (output,BorderLayout.CENTER); //TO ADD TextArea (output) AT THE CENTER OF THE WINDOW window.getContentPane().add (input,BorderLayout.SOUTH); //TO ADD THE Textbox (input) AT THE BOTTOM (SOUTH) protected DataInputStream dataIn; protected DataOutputStream dataOut; protected Thread listener; public synchronized void start () throws IOException { //THREAD SYNCHRONIZATION METHOD FOR STARTING BROADCAST if (listener == null) { Socket socket = new Socket (host, port); //TO INITIALIZE //THE SOCKET try { dataIn = new DataInputStream (new BufferedInputStream (socket.getInputStream ())); dataOut = new DataOutputStream (new BufferedOutputStream (socket.getOutputStream ())); dataOut.writeUTF (yourname+" has loggged on\n "); } catch (IOException ex) { socket.close (); throw ex; } } listener = new Thread (this); listener.start (); window.setVisible (true); } } public synchronized void stop () throws IOException //THREAD SYNCHRONIZATION METHOD FOR STOPPING THE BROADCAST { if (listener != null) { listener.interrupt (); listener = null; dataOut.close (); } public void run() { //THREAD METHOD FOR READING A NEW MESSAGE //LINE FROM THE CLIENT try { while (!Thread.interrupted ()) { String line = dataIn.readUTF (); output.append (line + "\n"); } } catch (IOException ex) { handleIOException (ex); } }

When the user runs the program and writes something on the input text box and presses Enter, the start ( ) method gets called to create a socket and to initialize the input stream and output stream to send the messages typed in by the client user to the server which then broadcast it to other clients. The run ( ) method is called as long as the conversation goes on to send the messages. When the user exits the program, the stop ( ) method is called that closes the socket connection.

Reference

The Code Reference classes were extracted from the book Java Network Programming by Merlin Hughes, Michael Shoffner, Derek Hamner, with Umesh Bellur, with additional functionality by Fatima Ahmed.

Downloads

Download demo project - 8.67 KB





Comment and Contribute

 


(Maximum characters: 1200). You have characters left.

 

 


Sitemap | Contact Us

Rocket Fuel