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.

3 comments: