Logo 
Search:

Java Articles

Submit Article
Home » Articles » Java » Socket ProgrammingRSS Feeds

Socket program of multi client chat server

Posted By: Easy Tutor     Category: Java     Views: 64265

Write a socket program of multi client chat server.

Code for Socket program of multi client chat server in Java

// Chat client

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

class chatClient extends Frame implements Runnable
{
    Socket soc;    
    TextField tf;
    TextArea ta;
    Button btnSend,btnClose;
    String sendTo;
    String LoginName;
    Thread t=null;
    DataOutputStream dout;
    DataInputStream din;
    chatClient(String LoginName,String chatwith) throws Exception
    {
        super(LoginName);
        this.LoginName=LoginName;
        sendTo=chatwith;
        tf=new TextField(50);
        ta=new TextArea(50,50);
        btnSend=new Button("Send");
        btnClose=new Button("Close");
        soc=new Socket("127.0.0.1",5217);

        din=new DataInputStream(soc.getInputStream()); 
        dout=new DataOutputStream(soc.getOutputStream());        
        dout.writeUTF(LoginName);

        t=new Thread(this);
        t.start();

    }
    void setup()
    {
        setSize(600,400);
        setLayout(new GridLayout(2,1));

        add(ta);
        Panel p=new Panel();
        
        p.add(tf);
        p.add(btnSend);
        p.add(btnClose);
        add(p);
        show();        
    }
    public boolean action(Event e,Object o)
    {
        if(e.arg.equals("Send"))
        {
            try
            {
                dout.writeUTF(sendTo + " "  + "DATA" + " " + tf.getText().toString());            
                ta.append("\n" + LoginName + " Says:" + tf.getText().toString());    
                tf.setText("");
            }
            catch(Exception ex)
            {
            }    
        }
        elseif(e.arg.equals("Close"))
        {
            try
            {
                dout.writeUTF(LoginName + " LOGOUT");
                System.exit(1);
            }
            catch(Exception ex)
            {
            }
            
        }
        
        return super.action(e,o);
    }
    publicstaticvoid main(String args[]) throws Exception
    {
        chatClient Client1=new chatClient(args[0],args[1]);
        Client1.setup();                
    }    
    publicvoid run()
    {        
        while(true)
        {
            try
            {
                ta.append( "\n" + sendTo + " Says :" + din.readUTF());
                
            }
            catch(Exception ex)
            {
                ex.printStackTrace();
            }
        }
    }
}

// Chat Server

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

class chatServer
{
    static Vector ClientSockets;
    static Vector LoginNames;
    
    chatServer() throws Exception
    {
        ServerSocket soc=new ServerSocket(5217);
        ClientSockets=new Vector();
        LoginNames=new Vector();

        while(true)
        {    
            Socket CSoc=soc.accept();        
            AcceptClient obClient=new AcceptClient(CSoc);
        }
    }
    publicstaticvoid main(String args[]) throws Exception
    {
        
        chatServer ob=new chatServer();
    }

class AcceptClient extends Thread
{
    Socket ClientSocket;
    DataInputStream din;
    DataOutputStream dout;
    AcceptClient (Socket CSoc) throws Exception
    {
        ClientSocket=CSoc;

        din=new DataInputStream(ClientSocket.getInputStream());
        dout=new DataOutputStream(ClientSocket.getOutputStream());
        
        String LoginName=din.readUTF();

        System.out.println("User Logged In :" + LoginName);
        LoginNames.add(LoginName);
        ClientSockets.add(ClientSocket);    
        start();
    }

    publicvoid run()
    {
        while(true)
        {
            
            try
            {
                String msgFromClient=new String();
                msgFromClient=din.readUTF();
                StringTokenizer st=new StringTokenizer(msgFromClient);
                String Sendto=st.nextToken();                
                String MsgType=st.nextToken();
                int iCount=0;
    
                if(MsgType.equals("LOGOUT"))
                {
                    for(iCount=0;iCount<LoginNames.size();iCount++)
                    {
                        if(LoginNames.elementAt(iCount).equals(Sendto))
                        {
                            LoginNames.removeElementAt(iCount);
                            ClientSockets.removeElementAt(iCount);
                            System.out.println("User " + Sendto +" Logged Out ...");
                            break;
                        }
                    }
    
                }
                else
                {
                    String msg="";
                    while(st.hasMoreTokens())
                    {
                        msg=msg+" " +st.nextToken();
                    }
                    for(iCount=0;iCount<LoginNames.size();iCount++)
                    {
                        if(LoginNames.elementAt(iCount).equals(Sendto))
                        {    
                            Socket tSoc=(Socket)ClientSockets.elementAt(iCount);                            
                            DataOutputStream tdout=new DataOutputStream(tSoc.getOutputStream());
                            tdout.writeUTF(msg);                            
                            break;
                        }
                    }
                    if(iCount==LoginNames.size())
                    {
                        dout.writeUTF("I am offline");
                    }
                    else
                    {
                        
                    }
                }
                if(MsgType.equals("LOGOUT"))
                {
                    break;
                }

            }
            catch(Exception ex)
            {
                ex.printStackTrace();
            }
            
            
            
        }        
    }
}
}
  
Share: 


Didn't find what you were looking for? Find more on Socket program of multi client chat server Or get search suggestion and latest updates.

Easy Tutor
Easy Tutor author of Socket program of multi client chat server is from United States. Easy Tutor says

Hello Friends,

I am Free Lance Tutor, who helped student in completing their homework.

I have 4 Years of hands on experience on helping student in completing their homework. I also guide them in doing their final year projects.

I have share many programs on this website for everyone to use freely, if you need further assistance, than please contact me on easytutor.2ya [at the rate] gmail [dot] com

I have special discount scheme for providing tutor services. I am providing tutor service to students from various contries, currently most of my students are from United States, India, Australia, Pakistan, Germany, UK and Canada.

I am also here to expand my technical network to receive more opportunity in my career, make friends to help them in resolving their technical problem, learn and share my knowledge, If you like to be my friend, Please send me friend request.

Thanks,
Happy Programming :)

 
View All Articles

Related Articles and Code:


 
Please enter your Comment

  • Comment should be atleast 30 Characters.
  • Please put code inside [Code] your code [/Code].

 
Jack Zain from Indonesia Comment on: Oct 24
how to work this script

Veen Dra from Indonesia Comment on: Aug 15
i try to run ur program
but i getting unusual error
please help me with the error

Mamitha Jayaram from India Comment on: Sep 26
Server and Client are running fine
but two arguments we have to provide
please tell the arguments to give

View All Comments