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

Sunday 24 June 2012

Create your own Chat Server in Java

here I am going to post how you can use Java to create a Chat Server successfully. You can use Java's networking package for this purpose. Along with this you will also need java.io package for sending and receiving data to and from client. We will use ServerSocket to create a server socket at a given PORT and a Socket object that will accept a connection. After the connection is set up with client you can chat easily. Here is the code that will create a GUI based Chat Server that has a Textfield for server to write and a TextArea that contains chat contents.

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

public class ChatServer {
   
    public static final int PORT=8080; //the port that will open
    boolean connected=false;
    ServerSocket servsock;
    Socket sock;
    BufferedReader br; //for reading client data
    PrintWriter pout; //for sending server data
   
    JFrame jf=new JFrame("Server");
    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()); //sending data
                     jta.append("Sending : "+jtf.getText()+"\n");
                     jtf.setText("");
                     jtf.requestFocus();
                 }
           }catch (Exception ex) {
                 System.out.println(ex.getMessage());
           }
        }
    };
   
    public ChatServer() {
        try{
           buildGUI();
        }catch(IOException 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{
            servsock = new ServerSocket(PORT);
            System.out.println("Started: " + servsock);
            try {
                  // Blocks until a connection occurs:
              sock = servsock.accept();
              try {
                System.out.println("Connection accepted: "+ 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 str = br.readLine(); //receiving data
                          if (str.equals("END")) break; /*type END to end connection. Open connection can or port can cause problem in future*/
                          if(str!="")
                          jta.append("Recieving: " +str+"\n");
                  }
                 // Always close the two sockets...
                } finally {
                   System.out.println("closing...");
                    sock.close();
                   }
                } finally {
                       servsock.close();
                        }
    }
   
    public static void main (String[] args) {
           new ChatServer();
    }
}


You can also directly download the source from below link
DOWNLOAD the source from Mediafire
NOTE : You need a Chat Client to set up the network without which you cannot test this code whether this code is working correctly or not. The Client side code will be posted very soon.