Wednesday 27 June 2012

Create your own Chat Client in Java

In my previous post I have mentioned that you cannot test the chat server code without the client code. So according to that today I will post the client code. Here also java.io and java.net packages are used for setting up the connection and for sending and receiving data. Here a Socket instance is created using the server ip adddress and port number through which it will connect to server. Then BufferedReader and PrintWriter is used for receiving and sending data. Here in the code below you will get a full GUI version of it.

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

public class ChatClient {
   
    boolean connected=false;
    Socket sock;
    BufferedReader br;
    PrintWriter pout;
   
    JFrame jf=new JFrame("ChatClient");
    JPanel
        jp1=new JPanel(),
        jp2=new JPanel(),
        mainpanel=new JPanel();
   
    JTextArea jta=new JTextArea(15,40);
    JLabel sendlabel=new JLabel("Server Text : ");
    JTextField jtf=new JTextField(20);
    JButton sendbutton=new JButton("Send");
   
    ActionListener sendlistener=new ActionListener(){
        public void actionPerformed(ActionEvent ev){
            try {
                 if(connected==true){
                     pout.println(jtf.getText());
                     jta.append("Sending : "+jtf.getText()+"\n");
                     if(jtf.getText().equals("END"))  connected=false;                    
                     jtf.setText("");
                     jtf.requestFocus();
                 }
           }catch (Exception ex) {
                 System.out.println(ex.getMessage());
           }
        }
    };

    public ChatClient() {
        try{
        buildGUI();
        }catch(Exception ex){
            System.out.println(ex.getMessage());
            }
    }
   
    public void buildGUI()throws IOException{
        jp1.setLayout(new BoxLayout(jp1,BoxLayout.X_AXIS));
        jp2.setLayout(new BoxLayout(jp2,BoxLayout.Y_AXIS));
       
        JScrollPane scroll=new JScrollPane(jta);
        scroll.setHorizontalScrollBarPolicy(ScrollPaneConstants.HORIZONTAL_SCROLLBAR_ALWAYS);
        scroll.setVerticalScrollBarPolicy(ScrollPaneConstants.VERTICAL_SCROLLBAR_ALWAYS);
       
        sendbutton.addActionListener(sendlistener);
        jta.setEditable(false);
        jta.setFont(new Font("serif",Font.PLAIN,16));
       
        jp1.add(sendlabel);             jp1.add(Box.createHorizontalStrut(5));
        jp1.add(jtf);                          jp1.add(Box.createHorizontalStrut(5));        jp1.add(sendbutton);
        jp2.add(jp1);        jp2.add(Box.createVerticalStrut(10));         jp2.add(scroll);
        mainpanel.add(jp2);
       
        jf.getContentPane().add(mainpanel);
        jf.pack();
        jf.setVisible(true);
        jf.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
       
        setupnetworking();
    }
   
    public void setupnetworking()throws IOException{
          InetAddress addr =InetAddress.getByName(null);
          System.out.println("addr = " + addr);
          sock =new Socket(addr, ChatServer.PORT);
// Guard everything in a try-finally to make
// sure that the socket is closed:
           try {
                System.out.println("socket = " + sock);
                connected=true;
                br =new BufferedReader(new InputStreamReader(sock.getInputStream()));
// Output is automatically flushed by PrintWriter:
               pout =new PrintWriter(new BufferedWriter(new OutputStreamWriter(sock.getOutputStream())),true);
             
                 while(true){
                     String message="";
                     if((message=br.readLine())!="")
                         jta.append("Recieved : "+message+"\n");
                     if(connected==false)  break;
                 }
               } catch(Exception ex) {
                      System.out.println(ex.getMessage());
               }
               finally{
                     System.out.println("closing...");
                  sock.close();
               }
    }
   
    public static void main (String[] args) {
        try{
              UIManager.setLookAndFeel("com.sun.java.swing.plaf.windows.WindowsLookAndFeel");
       }catch(Exception e){}
        new ChatClient();
    }
}


You can also download the source from below given link
 DOWNLOAD the source from Mediafire

No comments:

Post a Comment