Recently I have made a simple chatting application(in Java).
It has two classes one for client and one for server.On compiling it is not giving any error but on running, it is not giving desired result.

So, It will be grateful if you come ahead and try out helping me in any way , solving/correcting my program


Client class is:

package com;

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

public class ChatClient {
    JTextArea in;
    JTextField out;
    JButton button;
    BufferedReader reader;
    PrintWriter writer;
    Socket sock;

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

    public void go() {
        JFrame frame = new JFrame("Chat Application");
        JPanel panel = new JPanel();
        in=new JTextArea(15,50);
        in.setLineWrap(true);
        in.setWrapStyleWord(true);
        in.setEditable(false);
        JScrollPane scroller = new JScrollPane(in);
        scroller.setVerticalScrollBarPolicy(ScrollPaneConstants.VERTICAL_SCROLLBAR_ALWAYS);
        scroller.setHorizontalScrollBarPolicy(ScrollPaneConstants.HORIZONTAL_SCROLLBAR_NEVER);
        out=new JTextField(20);
        button=new JButton("SEND");
        button.addActionListener(new ButtonListener());
        panel.add(scroller);
        panel.add(out);
        panel.add(button);
        setUpNetworking();

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

        frame.getContentPane().add(BorderLayout.CENTER,panel);
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        frame.setSize(400,500);
        frame.setVisible(true);
    }

    public void setUpNetworking() {
        try {
            sock = new Socket("127.0.0.1",5000);
            InputStreamReader stream = new InputStreamReader(sock.getInputStream());
            reader = new BufferedReader(stream);
            writer = new PrintWriter(sock.getOutputStream());
            System.out.println("Network Established");
        }
        catch(IOException e) {
            e.printStackTrace();
        }
    }

    public class ButtonListener implements ActionListener {
        public void actionPerformed(ActionEvent ae) {
            try {
                writer.println(out.getText());
                writer.flush();
            }
            catch(Exception e) {
                e.printStackTrace();
            }
            out.setText(" ");
            out.requestFocus();
        }
    }

    public class IncomingReader implements Runnable {
        public void run() {
            String message;
            try {
                while((message=reader.readLine())!=null) {
                    System.out.println("raed "+message);
                    in.append(message+ "\n");
                }
            }
            catch(Exception e) {
                e.printStackTrace();
            }
        }
    }

}

Server class is:

package com;

import java.io.*;
import java.net.*;
import java.util.*;

public class ChatServer {
    ArrayList clientOutputStream;

    public static void main(String ar[]) {
        new ChatServer().go();
    }

    public void go() {
        clientOutputStream = new ArrayList();
        try {
            ServerSocket serverSock = new ServerSocket(5000);
            while(true) {
                Socket clientSocket = serverSock.accept();
                PrintWriter writer = new PrintWriter (clientSocket.getOutputStream());
                clientOutputStream.add(writer);

                Thread t = new Thread (new ClientHandler(clientSocket));
            }
        }
        catch(Exception e) {
            e.printStackTrace();
        }
    }

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

         public ClientHandler(Socket clientSocket) {
             try {
             sock=clientSocket;
             InputStreamReader stream = new InputStreamReader(sock.getInputStream());
             reader = new BufferedReader(stream);
             }
             catch(Exception e) {
                 e.printStackTrace();
             }
         }

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

         public void tellEveryOne(String message) {
             Iterator it = clientOutputStream.iterator();
             while(it.hasNext()) {
                 try {
                     PrintWriter writer = (PrintWriter)it.next();
                     writer.println(message);
                     writer.flush();
                 }
                 catch(Exception e) {
                     e.printStackTrace();
                 }
             }
         }
    }
}

Recommended Answers

All 17 Replies

it is not giving desired result.

Come on now, what is that telling us? Describe exactly what is going wrong - what exactly did you expect and what exactly did you get?

I guess he could have said what he meant by "desired result".
If you mean that your desired result is nothing showing up on the text area then I have messed with this for awhile, and try changing all of your buffered reader and print writers in all classes to a DataInputStream and DataOutputStream. Then use the methods readUTF and writeUTF.

Ye, somewhat you are true.
I am not getting anything on the text area, moreover on the server side I have put the code for printing the message to server on line no. 50 of server class. That's also not working,so check it out and if any more confusion be free to ask.

if after changing the BufferedReader and PrintWriter class it works then please paste the code here..

I don't see where you actually start this thread

Thread t = new Thread (new ClientHandler(clientSocket));

Try adding

t.start();

You may also want to put a check in your broadcast loop to not send to the person who typed the message.

No, I think you are wrong my dear friend, the sender of the message must also be vivible to him (for eq: in facebook also it is shown)..

Yeah, I suppose it's fine for chat. I was thinking about some recent network-based client synchronization code I was working on when I wrote that.

That suggestion was mostly just an afterthought though. My previous post about starting the thread addresses your current issue.

Your initial size on the frame is a bit too small, by the way. The responses are there, but you have to make the frame a little larger to see them.

Ye, somewhat you are true.
I am not getting anything on the text area, moreover on the server side I have put the code for printing the message to server on line no. 50 of server class. That's also not working,so check it out and if any more confusion be free to ask.

if after changing the BufferedReader and PrintWriter class it works then please paste the code here..

Try changing to the data types I mentioned, and start your threads. I debugged and trouble shooted your code for a good amount of hours and soon as I changed the data types it worked right away.

Yeah, I suppose it's fine for chat. I was thinking about some recent network-based client synchronization code I was working on when I wrote that.

SPeaking of synchronizing, that is also a good idea in the chat program....

private void broadcast(String message) {
			synchronized (handlers) { //Sync all client handlers
				Iterator<ClientHandler> it = handlers.iterator();//Get an iterator for each client handler

				//Get each client handler
				while( it.hasNext() ) {
					ClientHandler handler = it.next();

					try {
						synchronized (handler.outputWriter) {
							handler.outputWriter.writeUTF( message);
							handler.outputWriter.flush();
						}
					}
					catch(Exception e) {
						handler.stop();
					}
				}
			}
		}
	}

There is a nice article on java world about Building an Internet Chat system

First of all thanks for taking my problem seriously, and spending housr on it. If you have working code please paste it as till now I have not studied about writeUTF() function.

Do paste the complete working code , it will be helpful for me to learn some new more function etc.

Did you actually try what I posted yesterday about starting your client handler threads?

When I did that, your code worked just fine.

The thread you are talking about is already added in line no 23 of server class

Yes and you must call start() if you actually want to run it. Threads do not run themselves simply because you instantiate them.

That is why I said to add

t.start();

After changes you suggested it works that it is printed on each client side but why it is not showing anything on text area..

Here is my new Server class

package com;

import java.io.*;
import java.net.*;
import java.util.*;

public class ChatServer {
    ArrayList clientOutputStream;

    public static void main(String ar[]) {
        new ChatServer().go();
    }

    public void go() {
        clientOutputStream = new ArrayList();
        try {
            ServerSocket serverSock = new ServerSocket(5000);
            while(true) {
                Socket clientSocket = serverSock.accept();
                PrintWriter writer = new PrintWriter (clientSocket.getOutputStream());
                clientOutputStream.add(writer);

                Thread t = new Thread (new ClientHandler(clientSocket));
                t.start();
                System.out.println(" Got a Connection");
            }
        }
        catch(Exception e) {
            e.printStackTrace();
        }
    }

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

         public ClientHandler(Socket clientSocket) {
             try {
             sock=clientSocket;
             InputStreamReader stream = new InputStreamReader(sock.getInputStream());
             reader = new BufferedReader(stream);
             }
             catch(Exception e) {
                 e.printStackTrace();
             }
         }

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

         public void tellEveryOne(String message) {
             Iterator it = clientOutputStream.iterator();
             while(it.hasNext()) {
                 try {
                     PrintWriter writer = (PrintWriter)it.next();
                     writer.println(message);
                     writer.flush();
                 }
                 catch(Exception e) {
                     e.printStackTrace();
                 }
             }
         }
    }
}

First of all thanks for taking my problem seriously, and spending housr on it. If you have working code please paste it as till now I have not studied about writeUTF() function.

Do paste the complete working code , it will be helpful for me to learn some new more function etc.

writeUTF and readUTF is not that complicated, i didn't study it at all but I understand it's behavior.

If you want the code still then here it is, even has sound for when sending a message and a timestamp/clock for each message.

package Client;
/**
 * File: ChatClient.java
 * ChatClient represents a graphical user program that sends and receives messages to a chat server
 * In order for the chat client to start sending and receiving messages, the user has to give a user name first.
 * It listens for incoming messages from a server and when it has messages, displays it to the screen.
 * @author Anthony Turner
 * 
 */
import java.io.*;
import java.net.*;
import javax.swing.*;
import javax.swing.UIManager.LookAndFeelInfo;
import javax.swing.text.Document;
import java.awt.event.*;
import java.awt.*;

public class ChatClient extends JFrame implements Runnable, ItemListener, FileMenuConstants, ButtonNameConstants{

	//Constant fields
	private static final long serialVersionUID = 1L;
	private static final int FRAME_WIDTH = 800;
	private static final int FRAME_HEIGHT = 600;
	//Instance fields
	private JEditorPane displayArea;
	private JTextField inputField;
	private ChatClientHandler clientHandler = new ChatClientHandler();
	private Socket socket; //Creates a connection to a server
	private DataInputStream inputReader; //Reads in server socket data output
	private DataOutputStream outputWriter;//Writes out client socket data
	private Thread clientListener; //Listens for incoming server messages
	private Clock clock = new Clock();
	private Person account;

	/**
	 * Constructs a new ChatClient
	 */
	public ChatClient(){
		setupFrame();
		setupThread();
		setVisible(true);

	}

	/**
	 * Gets the client handler for the chat client
	 * @return Returns a client handler for component action events
	 */
	public ChatClientHandler getClientHandler(){
		return clientHandler;
	}

	/*
	 * Shows a network setup dialog for entering host and port info
	 */
	private void showNetworkSetup(){
		String host = JOptionPane.showInputDialog(this , "Enter Host:");
		
		if(host != null ){//Check that the host name is not empty
			
			String port = JOptionPane.showInputDialog(this , "Enter Port:");
			
			if(port != null){//Check that the port name is not empty
				
				//If we made it here then we can setup a new network connection
				setupSession(host, Integer.parseInt( port ));
			}
		}
	}

	/*
	 * Sets up a new client to server session
	 */
	private void setupSession(String host, int port) {
		try {
			socket = new Socket(host, port);
			System.out.println("Socket connected");

			//Reads input in from a socket connection ( server )
			inputReader = new DataInputStream( socket.getInputStream() );

			//Writes output to a socket connection ( server );
			outputWriter = new DataOutputStream( socket.getOutputStream() );

			System.out.println("Network Established");
			sendMessage(account.getName(), " joined the room.");
			if( !clientListener.isAlive() ){
				clientListener.start();
			}

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

	public void setupFrame() {


		setTitle("Java Chat Application");
		setLayout( new BorderLayout());
		setIconImage( new ImageIcon("images/frameIcon.png").getImage());
		setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
		setLocation(800 /2,600/2);
		setSize(FRAME_WIDTH,FRAME_HEIGHT);
		setJMenuBar( new ChatJMenuBar(this));


		//Display text area
		displayArea  = new JEditorPane();
		displayArea.setEditable(false);
		displayArea.setBorder(BorderFactory.createEmptyBorder(4, 4, 4, 4));
		displayArea.setFont(new Font("Arial", Font.PLAIN, 15));


		JScrollPane sp = new JScrollPane(displayArea);
		sp.setVerticalScrollBarPolicy(ScrollPaneConstants.VERTICAL_SCROLLBAR_ALWAYS);
		sp.setHorizontalScrollBarPolicy(ScrollPaneConstants.HORIZONTAL_SCROLLBAR_NEVER);
		add(sp);

		createTopLayout();
		createEastLayout();
		createBottomLayout();


	}

	/*
	 * Creates the east layouts components
	 */
	private void createEastLayout() {

		JPanel panel = new JPanel();
		JTextArea roomList = new JTextArea(50,6);
		roomList.setEditable( false );
		//roomList.add( new JLabel("Room"));
		panel.add( roomList);
		add(panel, BorderLayout.EAST);

	}


	/*
	 * Creates the south layouts components
	 */
	private void createBottomLayout() {
		JPanel bottomPanel = new JPanel();
		//	bottomPanel.setBackground(Color.black);

		//Input text field
		inputField = new JTextField(20);
		inputField.setRequestFocusEnabled(true);
		inputField.setActionCommand(SEND_BUTTON);
		inputField.addActionListener( clientHandler );

		bottomPanel.add(inputField);

		//Send button
		JButton sendButton = new JButton(SEND_BUTTON);
		sendButton.addActionListener( clientHandler );
		bottomPanel.add(sendButton);
		
		add( bottomPanel, BorderLayout.SOUTH);

	}


	/*
	 * Creates the north layouts components
	 */
	private void createTopLayout(){

		JToolBar toolBar = new JToolBar();		
		toolBar.setBorder( BorderFactory.createEtchedBorder() );

		String[]names = {CONNECT_BUTTON, DISCONNECT_BUTTON};
		for(int i = 0; i < names.length; i++){
			JButton button =  new JButton(names[i]);
			button.addActionListener( clientHandler );
			toolBar.add( button) ;

		}
		add(toolBar, BorderLayout.NORTH);
	}

	/*
	 * Create a themes panel for the chat client
	 */
	private void showThemesPanel(){

		JDialog themeDiag = new JDialog( );
		themeDiag.add( new ThemesPanel(this) );
		themeDiag.setLocationRelativeTo( this );
		themeDiag.setModal(true);
		themeDiag.pack();
		themeDiag.setVisible(true);
	}

	/*
	 * Shows an Account setup dialog for creating a new account
	 */
	private void showNewAccountSetup() {

		String name = JOptionPane.showInputDialog(this, "User Name:");	
		if( name != null && name.length() >0){
			account = new Person(name);//Create the users account
			showNetworkSetup();//Display network setup info
		}
	}


	/*
	 * Sets up and starts a thread for listening for server messages
	 */
	private void setupThread() {
		clientListener = new Thread( this );
	}

	@SuppressWarnings("deprecation")
	@Override
	/**
	 * This method continuously loops reading in any input that it gets from the server
	 * It then adds it to the display text area of the client
	 */
	public void run() {

		try {
			int count = 0;
			while( true ) {
				String message = inputReader.readUTF();
				Document doc = (Document)displayArea.getDocument();
				doc.insertString(doc.getEndPosition().getOffset(), "["+ clock.getTime()+"]" + " " +  message  +"\n",null);	
				count++;
			}
		}catch(Exception e) {
			e.printStackTrace();
		}finally{
			clientListener = null;
			inputField.hide ();
			validate();
			try{
				outputWriter.close();
			}catch(Exception e){
				e.printStackTrace();
			}
		}
	}

	/**
	 * ChatClientHandler handles action events for the chat client
	 * @author Anthony Turner
	 *
	 */
	class ChatClientHandler implements ActionListener{


		@Override
		public void actionPerformed(ActionEvent event) {
			
			if( event.getSource() instanceof JButton || event.getSource() instanceof JTextField){
				checkButtonActionEvents(event);
			}else if( event.getSource() instanceof JMenu || event.getSource() instanceof JMenuItem){
				checkMenuActionEvents(event);
			}
		}

		/*
		 * Checks menu action events
		 */
		private void checkMenuActionEvents(ActionEvent event){
			if( event.getActionCommand().equals( MI_NEW)){
				showNewAccountSetup();
			}else if( event.getActionCommand().equals( MI_THEMES)){
				showThemesPanel();
			} else if( event.getActionCommand().equals( MI_EXIT)){
				System.exit(0);
			}
		}

		/*
		 * Checks button action events
		 */
		private void checkButtonActionEvents(ActionEvent event) {

			if( event.getActionCommand().equals( SEND_BUTTON )  && clientListener.isAlive() ){
				String input = inputField.getText();

				if(input != null && input.length() >0 && !input.startsWith("\n")){
					 
					sendMessage(account.getName(), input);
					ChatSound.play(ChatSound.SUBMIT_SOUND);		

				}
			}else if( event.getActionCommand().equals( CONNECT_BUTTON)){

				if( account != null)showNetworkSetup();

			}else if( event.getActionCommand().equals( DISCONNECT_BUTTON)){
				synchronized (clientListener) {
					clientListener.stop();	
				}
				
			}			
		}


	}

	private void sendMessage(String user, String message) {
		try {

			outputWriter.writeUTF( user +"> " + message );
			outputWriter.flush(); //Flush the output writer so that text is sent immediately

			inputField.setText(" "); //Clear text from the text field
			inputField.requestFocus();//Set the input field to focused

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

	@Override
	public void itemStateChanged(ItemEvent e) {

	}

	public static void main(String[] args){

		LookAndFeelInfo[] lnf = UIManager.getInstalledLookAndFeels();

		try {
			UIManager.setLookAndFeel(lnf[1].getClassName() );
			new ChatClient();
		} catch (Exception e) {

			e.printStackTrace();
		}
	}
}
package Server;
/**
 * File: ChatServer.java
 * ChatServer represents a server for each connected client
 * The server continuously listens for incoming client messages
 * It then relays the messages back to all clients connected
 * Clients are all synchronized so that messages are not received in the wrong order
 * @author Anthony Turner
 * 
 */
import java.io.*;
import java.net.*;
import java.util.*;
import javax.swing.JOptionPane;

public class ChatServer {

	//Constant fields
	protected static Vector<ClientHandler> handlers = new Vector<ClientHandler>();
	//Instance fields
	public static final int PORT = 5000;

	
	/**
	 * Constructs a new ChatServer
	 */
	public ChatServer(){
		this(PORT);
	}
	
	/**
	 * Constructs a new one parameterized ChatServer
	 */
	public ChatServer(int port){
			startServer(port);
	}

	public void startServer(int port) {
		
		try {
			//create a new server socket connection
			ServerSocket server = new ServerSocket(port);
			//Keep looping accepting connections
			while(true) {
				Socket client = server.accept();//Accepts a client connection
				System.out.println("Accepted connection from " + client.getInetAddress ());
				
				ClientHandler c = new ClientHandler(client);//Handles each new connection
				c.start();//Start a thread for the new connection

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

	/**
	 * ClientHandler handles the clients that connect to this server
	 * It reads in clients messages and then broadcast them out to all clients
	 * @author Anthony Turner
	 *
	 */
	public class ClientHandler extends Thread{

		//Instance fields
		private DataInputStream inputReader;
		private DataOutputStream outputWriter;
		private Socket socket;

		/**
		 * Constructs a new ClientHandler
		 * @param clientSocket The clients socket connection
		 */
		public ClientHandler(Socket clientSocket) {
			
			try {
				socket = clientSocket;
				//Reads in input from the client ( chat client )
				inputReader = new DataInputStream( socket.getInputStream() );

				//Writes out output to the client ( chat client )
				outputWriter = new DataOutputStream( socket.getOutputStream());

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

		@Override
		public void run() {
			try {
				handlers.addElement(this);

				while(true) {
					String message = inputReader.readUTF();
					broadcast(message);
				}
			}catch(Exception e) {
				//e.printStackTrace(); //Throws an error fix
			}finally{
				handlers.removeElement( this );
			}
			try {
				socket.close ();
			} catch (IOException ex) {
				ex.printStackTrace();
			}

		}

		private void broadcast(String message) {
			synchronized (handlers) { //Sync all client handlers
				Iterator<ClientHandler> it = handlers.iterator();//Get an iterator for each client handler

				//Get each client handler
				while( it.hasNext() ) {
					ClientHandler handler = it.next();

					try {
						synchronized (handler.outputWriter) {
							handler.outputWriter.writeUTF( message);
							handler.outputWriter.flush();
						}
					}
					catch(Exception e) {
						handler.stop();
					}
				}
			}
		}
	}

	private static void showDialog() {
		String port = JOptionPane.showInputDialog("Enter port for server:");
		if(port != null){
			new ChatServer( Integer.parseInt( port ));
		}		
	}
	
	public static void main(String[]args){
			showDialog();
	}
}

I still have to work out some exception handling.
The full program is in an attachment zipped.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.