image source Google search


                          My Previous post based on Swing-JDBC-Database. Now i thought that i never post any Network related post till. That's why i am showing here is Chat Application. But one thing i need to clear our blog readers this is not a full Chat application. My motive of this post to know ever one  concepts and how to implement real time. Okay come to the point First see the following  diagram for better understanding.


Here we need start the server first after that you need to login form once it is validate then only open client application.Here one more thing i need to clarify i.e., each client is acting one user that means suppose me and you are chatting then open two client application. Okay now come to coding part now first showing LoginForm



LoginForm.java

/****************************************************************
* Description
* This is a Login frame of client side application in chat System.
* It is used to just take the user name 
*
* Remarks
* Before running the Login application make sure the server is running.
* If server is running then only you can execute your application.
******************************************************************/


import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
import java.io.*;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.*;

// Login class which takes a user name and passed it to client class
public class Login implements ActionListener{
JFrame frame1;
JTextField tf;
JTextField tf1;
JButton button;
JLabel heading;
JLabel label;
JLabel label1;
static Connection con;
public static void main(String[] args){
new Login();
}
public Login(){
frame1 = new JFrame("Login Page");
tf=new JTextField();
tf1=new JTextField();
button=new JButton("Login");
heading=new JLabel("Chat Server");
heading.setFont(new Font("Impact", Font.BOLD,35));
label=new JLabel("Enter you Login User Name");
label.setFont(new Font("Serif", Font.PLAIN, 24));
label1=new JLabel("Enter you Login Password Name");
label1.setFont(new Font("Serif", Font.PLAIN, 24));
JPanel panel = new JPanel();
button.addActionListener(this);
panel.add(heading);panel.add(tf);panel.add(tf1);panel.add(label);panel.add(label1);
panel.add(button);
heading.setBounds(30,20,280,80);
label.setBounds(20,100,250,60);
tf.setBounds(50,150,150,30);
label1.setBounds(20,155,250,60);
tf1.setBounds(50,200,150,30);
button.setBounds(70,250,90,30);
frame1.add(panel);
panel.setLayout(null);
frame1.setSize(300, 300);
   frame1.setVisible(true);
frame1.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
getConnection();
}
public static Connection getConnection(){
try{
Class.forName("com.mysql.jdbc.Driver");
String url ="jdbc:mysql://localhost:3306/test";
con = DriverManager.getConnection(url,"root","root");
    }catch(Exception e){
    e.printStackTrace();
    }
    return con;
}
// pass the user name to MyClient class
public void actionPerformed(ActionEvent e){
String name="";
String name1="";
Statement st = null;
ResultSet rs = null;
boolean more = false;
try{
name=tf.getText();
name1=tf1.getText();
// Build the query  SELECT * FROM users WHERE username='...' AND password= '...' 
   String searchQuery =
       "select * from users where username='"
           + name
           + "' AND password='"
           + name1
           + "'";
 
try {
st = con.createStatement();
rs = st.executeQuery(searchQuery);
more = rs.next();
} catch (SQLException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}// If 'rs' is empty, then more = false; else, more = true
    // If the ResultSet is empty >>> user does not exist >>> set the isValid variable to false
    if (more) 
    {
frame1.dispose();
   MyClient mc=new MyClient(name);
}else
{
System.out.println("exit");
 
}
}catch (IOException te){}
}
}


Now Network Package is implemented in server application see that code once.

MyServer.Java

/****************************************************************
* Description
* This is a Server Side application of Chat System.
* This application is used for receiving the messages from any client
* and send to each and every client and in this we can maintain the
* list of all online users.
*
* Remarks
* This application is unable to provide the private chatting facility
******************************************************************/

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

public class MyServer{
ServerSocket ss;
Socket s;
ArrayList al=new ArrayList();
ArrayList al1=new ArrayList();
ArrayList al2=new ArrayList();
ArrayList alname=new ArrayList();
Socket s1,s2;
MyServer()throws IOException{
ss=new ServerSocket(1004); // create server socket
while(true){
s=ss.accept(); //accept the client socket
s1=ss.accept();
s2=ss.accept();
al.add(s); // add the client socket in arraylist
al1.add(s1);
al2.add(s2);
System.out.println("Client is Connected");
MyThread2 m=new MyThread2(s2,al2,alname); //new thread for maintaning the list of user name
Thread t2=new Thread(m);
t2.start();

MyThread r=new MyThread(s,al);//new thread for receive and sending the messages
Thread t=new Thread(r);
t.start();
MyThread1 my=new MyThread1(s1,al1,s,s2); // new thread for update the list of user name
Thread t1=new Thread(my);
t1.start();
}
}
public static void main(String[] args){
try{
new MyServer();
}catch (IOException e){}
}
}
//class is used to update the list of user name
class MyThread1 implements Runnable{
Socket s1,s,s2;
static ArrayList al1;
DataInputStream ddin;
String sname;
MyThread1(Socket s1,ArrayList al1,Socket s,Socket s2){
this.s1=s1;
this.al1=al1;
this.s=s;
this.s2=s2;
}
public void run(){
try{
ddin=new DataInputStream(s1.getInputStream());
while(true){
sname=ddin.readUTF();
System.out.println("Exit  :"+sname);
MyThread2.alname.remove(sname);//remove the logout user name from arraylist
MyThread2.every();
al1.remove(s1);
MyThread.al.remove(s);
MyThread2.al2.remove(s2);
if(al1.isEmpty())
System.exit(0); //all client has been logout
}
}catch(Exception ie){}
}
}

// class is used to maintain the list of all online users
class MyThread2 implements Runnable{
Socket s2;
static ArrayList al2;
static ArrayList alname;
static DataInputStream din1;
static DataOutputStream dout1;

MyThread2(Socket s2,ArrayList al2,ArrayList alname){
this.s2=s2;
this.al2=al2;
this.alname=alname;
}
public void run(){
try{
din1= new DataInputStream(s2.getInputStream());
alname.add(din1.readUTF()); // store the user name in arraylist
every();
}catch(Exception oe){System.out.println("Main expression"+oe);}
}
// send the list of user name to all client
static void every()throws Exception{
Iterator i1=al2.iterator();
Socket st1;

while(i1.hasNext()){
st1=(Socket)i1.next();
dout1=new DataOutputStream(st1.getOutputStream());
ObjectOutputStream obj=new ObjectOutputStream(dout1);
obj.writeObject(alname); //write the list of users in stream of all clients
dout1.flush();
obj.flush();
}
}
}
//class is used to receive the message and send it to all clients
class MyThread implements Runnable{
Socket s;
static ArrayList al;
DataInputStream din;
DataOutputStream dout;

MyThread(Socket s, ArrayList al){
this.s=s;
this.al=al;
}
public void run(){
String str;
int i=1;
try{
din=new DataInputStream(s.getInputStream());
}catch(Exception e){}
while(i==1){
try{
str=din.readUTF(); //read the message
distribute(str);
}catch (IOException e){}
}
}
// send it to all clients
public void distribute(String str)throws IOException{
Iterator i=al.iterator();
Socket st;
while(i.hasNext()){
st=(Socket)i.next();
dout=new DataOutputStream(st.getOutputStream());
dout.writeUTF(str);
dout.flush();
}
}
}

This is client side application code MyClient.java

/****************************************************************
* Description
* This is a client side of chat application.
* This application is used to sending and receiving the messages
* and in this we can maintain the list of all online users
*
* Remarks
* Before running the client application make sure the server is 
* running.If server is running then only you can execute your
* application.
******************************************************************/
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
import java.io.*;
import java.net.*;
import java.util.ArrayList;
import java.util.Iterator;

//create the GUI of the client side
public class MyClient extends WindowAdapter implements ActionListener{
JFrame frame;
JList list;
JList list1;
JTextField tf;
DefaultListModel model;
DefaultListModel model1;
JButton button;
JButton lout;
JScrollPane scrollpane;
JScrollPane scrollpane1;
JLabel label;
Socket s,s1,s2;
DataInputStream din;
DataOutputStream dout;
DataOutputStream dlout;
DataOutputStream dout1;
DataInputStream din1;
String name;
MyClient(String name)throws IOException{
frame = new JFrame("Client Side");
tf=new JTextField();
model=new DefaultListModel();
model1=new DefaultListModel();
label=new JLabel("Message");
list=new JList(model);
list1=new JList(model1);
button=new JButton("Send");
lout=new JButton("Logout");
scrollpane=new JScrollPane(list);
scrollpane1=new JScrollPane(list1);
JPanel panel = new JPanel();
button.addActionListener(this);
lout.addActionListener(this);
panel.add(tf);panel.add(button);panel.add(scrollpane);
panel.add(label);panel.add(lout);
panel.add(scrollpane1);
scrollpane.setBounds(10,20,180,150);
scrollpane1.setBounds(250,20,100,150);
label.setBounds(20,180,80,30);
tf.setBounds(100,180,140,30);
button.setBounds(260,180,90,30);
lout.setBounds(260,230,90,30);
frame.add(panel);
panel.setLayout(null);
frame.setSize(400, 400);
  frame.setVisible(true);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
this.name=name;
frame.addWindowListener(this);
s=new Socket("localhost",1004); //creates a socket object
s1=new Socket("localhost",1004);
s2=new Socket("localhost",1004);
   //create inputstream for a particular socket
din=new DataInputStream(s.getInputStream());
//create outputstream
dout=new DataOutputStream(s.getOutputStream());
//sending a message for login
dout.writeUTF(name+" has Logged in");
dlout=new DataOutputStream(s1.getOutputStream());
dout1=new DataOutputStream(s2.getOutputStream());
din1=new DataInputStream(s2.getInputStream());

// creating a thread for maintaning the list of user name
My1 m1=new My1(dout1,model1,name,din1);
Thread t1=new Thread(m1);
t1.start();
//creating a thread for receiving a messages
My m=new My(din,model);
Thread t=new Thread(m);
t.start();
  }
public void actionPerformed(ActionEvent e){
// sending the messages
if(e.getSource()==button){
String str="";
str=tf.getText();
tf.setText("");
str=name+": > "+str;
try{
dout.writeUTF(str);
System.out.println(str);
dout.flush();
}catch(IOException ae){System.out.println(ae);}
}
// client logout
if (e.getSource()==lout){
frame.dispose();
try{
//sending the message for logout
dout.writeUTF(name+" has Logged out");
dlout.writeUTF(name);
dlout.flush();
Thread.currentThread().sleep(1000);
System.exit(1);
}catch(Exception oe){}
}
}
public void windowClosing(WindowEvent w){
try{
dlout.writeUTF(name);
dlout.flush();
Thread.currentThread().sleep(1000);
System.exit(1);
}catch(Exception oe){}
}
}

// class is used to maintaning the list of user name
class My1 implements Runnable{
DataOutputStream dout1;
DefaultListModel model1;
DataInputStream din1;
String name,lname;
ArrayList alname=new ArrayList(); //stores the list of user names
ObjectInputStream obj; // read the list of user names
int i=0;
My1(DataOutputStream dout1,DefaultListModel model1,String name,DataInputStream din1){
this.dout1=dout1;
this.model1=model1;
this.name=name;
this.din1=din1;
}
public void run(){
try{
dout1.writeUTF(name);  // write the user name in output stream
while(true){
obj=new ObjectInputStream(din1);
//read the list of user names
alname=(ArrayList)obj.readObject(); 
if(i>0)
model1.clear(); 
Iterator i1=alname.iterator();
System.out.println(alname);
while(i1.hasNext()){
lname=(String)i1.next();
i++;
//add the user names in list box
model1.addElement(lname);
}
}
}catch(Exception oe){}
}
}
//class is used to received the messages
class My implements Runnable{
DataInputStream din;
DefaultListModel model;
My(DataInputStream din, DefaultListModel model){
this.din=din;
this.model=model;
}
public void run(){
String str1="";
while(true){
try{
str1=din.readUTF(); // receive the message
// add the message in list box
model.addElement(str1);
}catch(Exception e){}
}
}
}

Note: Every JDBC application need database related jar file so for this application also you need add according Database depended jar file.



Post a Comment

 
Top