SlideShare a Scribd company logo
Firstly run myserver.java then run login.java
//Login page
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
import java.io.*;
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;
JButton button;
JLabel heading;
JLabel label;
public static void main(String[] args){
new Login();
}
public Login(){
frame1 = new JFrame("Login Page");
tf=new JTextField();
button=new JButton("Login");
heading=new JLabel("Chat Server");
heading.setFont(new Font("Impact", Font.BOLD,40));
label=new JLabel("Enter you Login Name");
label.setFont(new Font("Serif", Font.PLAIN, 24));
JPanel panel = new JPanel();
button.addActionListener(this);
panel.add(heading);panel.add(tf);panel.add(label);
panel.add(button);
heading.setBounds(30,20,280,80);
label.setBounds(20,100,250,60);
tf.setBounds(50,150,150,30);
button.setBounds(70,200,90,30);
frame1.add(panel);
panel.setLayout(null);
frame1.setSize(300, 300);
frame1.setVisible(true);
frame1.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
// pass the user name to MyClient class
public void actionPerformed(ActionEvent e){
String name="";
try{
name=tf.getText();
frame1.dispose();
MyClient mc=new MyClient(name);
//MyServer ms=new MyServer();
}catch (IOException te){}
}
}
//MyServer.java
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();
}
}
}
//MyClient.java
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;
JTextArea tf;
DefaultListModel model;
DefaultListModel model1;
JButton button;
JButton lout;
JScrollPane scrollpane;
JScrollPane scrollpane1;
JLabel label,label2,label3;
Socket s,s1,s2;
DataInputStream din;
DataOutputStream dout;
DataOutputStream dlout;
DataOutputStream dout1;
DataInputStream din1;
String name;
MyClient(String name)throws IOException{
frame = new JFrame("Chat Window");
frame.setLocation(375,100);
tf=new JTextArea();
model=new DefaultListModel();
model1=new DefaultListModel();
label=new JLabel("Message");
label2=new JLabel("Onilne Users");
label3=new JLabel("Chatting Messages");
list=new JList(model);
list1=new JList(model1);
button=new JButton("Send");
lout=new JButton("Back");
scrollpane=new JScrollPane(list);
scrollpane1=new JScrollPane(list1);
//from here
scrollpane.getVerticalScrollBar().addAdjustmentListener(new
AdjustmentListener() {
public void adjustmentValueChanged(AdjustmentEvent e) {
e.getAdjustable().setValue(e.getAdjustable().getMaximum());
}
});
scrollpane1.getVerticalScrollBar().addAdjustmentListener(new
AdjustmentListener() {
public void adjustmentValueChanged(AdjustmentEvent e) {
e.getAdjustable().setValue(e.getAdjustable().getMaximum());
}
});
//try
JPanel panel = new JPanel();
button.addActionListener(this);
lout.addActionListener(this);
panel.add(tf);panel.add(button);panel.add(scrollpane);
panel.add(label);panel.add(label2);panel.add(label3);panel.add(lout);
panel.add(scrollpane1);
scrollpane.setBounds(10,40,250,300);
scrollpane1.setBounds(350,40,150,300);
label.setBounds(10,350,80,30);
label2.setBounds(350,20,150,20);
label3.setBounds(10,20,250,20);
tf.setBounds(10,380,380,70);
button.setBounds(410,380,90,30);
lout.setBounds(410,420,90,30);
frame.add(panel);
panel.setLayout(null);
frame.setSize(550,500);
frame.setResizable(false);
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();
//new Welcome();
JOptionPane.showMessageDialog(null,"Return Back to
Welcome page");
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){}
}
}
}

More Related Content

What's hot

Collections and its types in C# (with examples)
Collections and its types in C# (with examples)Collections and its types in C# (with examples)
Collections and its types in C# (with examples)
Aijaz Ali Abro
 
Android studio installation
Android studio installationAndroid studio installation
Android studio installation
PoojaBele1
 
Java 8 Lambda Built-in Functional Interfaces
Java 8 Lambda Built-in Functional InterfacesJava 8 Lambda Built-in Functional Interfaces
Java 8 Lambda Built-in Functional Interfaces
Ganesh Samarthyam
 
Regular Expressions in Java
Regular Expressions in JavaRegular Expressions in Java
Regular Expressions in Java
OblivionWalker
 
Java interfaces
Java interfacesJava interfaces
Java interfaces
Raja Sekhar
 
Database in Android
Database in AndroidDatabase in Android
Database in Android
MaryadelMar85
 
Home appliances control system
Home appliances control systemHome appliances control system
Home appliances control system
Sundas Kayani
 
JavaFX Overview
JavaFX OverviewJavaFX Overview
JavaFX Overview
José Maria Silveira Neto
 
Swing and AWT in java
Swing and AWT in javaSwing and AWT in java
Swing and AWT in java
Adil Mehmoood
 
Java 8 Lambda and Streams
Java 8 Lambda and StreamsJava 8 Lambda and Streams
Java 8 Lambda and Streams
Venkata Naga Ravi
 
Java swing
Java swingJava swing
Java swing
Apurbo Datta
 
Exception handling in plsql
Exception handling in plsqlException handling in plsql
Exception handling in plsql
Arun Sial
 
Java: GUI
Java: GUIJava: GUI
Java: GUI
Tareq Hasan
 
python Function
python Function python Function
python Function
Ronak Rathi
 
Android UI
Android UIAndroid UI
Android UI
nationalmobileapps
 
Interface
InterfaceInterface
Interface
kamal kotecha
 
SQLITE Android
SQLITE AndroidSQLITE Android
SQLITE Android
Sourabh Sahu
 
Data Persistence in Android with Room Library
Data Persistence in Android with Room LibraryData Persistence in Android with Room Library
Data Persistence in Android with Room Library
Reinvently
 

What's hot (20)

Collections and its types in C# (with examples)
Collections and its types in C# (with examples)Collections and its types in C# (with examples)
Collections and its types in C# (with examples)
 
Android studio installation
Android studio installationAndroid studio installation
Android studio installation
 
Java 8 Lambda Built-in Functional Interfaces
Java 8 Lambda Built-in Functional InterfacesJava 8 Lambda Built-in Functional Interfaces
Java 8 Lambda Built-in Functional Interfaces
 
Regular Expressions in Java
Regular Expressions in JavaRegular Expressions in Java
Regular Expressions in Java
 
Java interfaces
Java interfacesJava interfaces
Java interfaces
 
Database in Android
Database in AndroidDatabase in Android
Database in Android
 
Home appliances control system
Home appliances control systemHome appliances control system
Home appliances control system
 
JavaFX Overview
JavaFX OverviewJavaFX Overview
JavaFX Overview
 
Swing and AWT in java
Swing and AWT in javaSwing and AWT in java
Swing and AWT in java
 
Java 8 Lambda and Streams
Java 8 Lambda and StreamsJava 8 Lambda and Streams
Java 8 Lambda and Streams
 
Java practical
Java practicalJava practical
Java practical
 
Java swing
Java swingJava swing
Java swing
 
Exception handling in plsql
Exception handling in plsqlException handling in plsql
Exception handling in plsql
 
Java: GUI
Java: GUIJava: GUI
Java: GUI
 
Collections in-csharp
Collections in-csharpCollections in-csharp
Collections in-csharp
 
python Function
python Function python Function
python Function
 
Android UI
Android UIAndroid UI
Android UI
 
Interface
InterfaceInterface
Interface
 
SQLITE Android
SQLITE AndroidSQLITE Android
SQLITE Android
 
Data Persistence in Android with Room Library
Data Persistence in Android with Room LibraryData Persistence in Android with Room Library
Data Persistence in Android with Room Library
 

Similar to Chat application in java using swing and socket programming.

You are to simulate a dispatcher using a priority queue system in C+.pdf
You are to simulate a dispatcher using a priority queue system in C+.pdfYou are to simulate a dispatcher using a priority queue system in C+.pdf
You are to simulate a dispatcher using a priority queue system in C+.pdf
JUSTSTYLISH3B2MOHALI
 
Why following sort does not work (It does not sort last 2 - 3 numbe.pdf
Why following sort does not work (It does not sort last 2 - 3 numbe.pdfWhy following sort does not work (It does not sort last 2 - 3 numbe.pdf
Why following sort does not work (It does not sort last 2 - 3 numbe.pdf
gopalk44
 
Java awt
Java awtJava awt
CodeZipButtonDemo.javaCodeZipButtonDemo.java Demonstrate a p.docx
CodeZipButtonDemo.javaCodeZipButtonDemo.java Demonstrate a p.docxCodeZipButtonDemo.javaCodeZipButtonDemo.java Demonstrate a p.docx
CodeZipButtonDemo.javaCodeZipButtonDemo.java Demonstrate a p.docx
mary772
 
CodeZipButtonDemo.javaCodeZipButtonDemo.java Demonstrate a p.docx
CodeZipButtonDemo.javaCodeZipButtonDemo.java Demonstrate a p.docxCodeZipButtonDemo.javaCodeZipButtonDemo.java Demonstrate a p.docx
CodeZipButtonDemo.javaCodeZipButtonDemo.java Demonstrate a p.docx
mccormicknadine86
 
Program klik sederhana
Program klik sederhanaProgram klik sederhana
Program klik sederhana
Henfry Kai
 
import java.awt.FlowLayout;import java.awt.event.KeyEvent;import.pdf
import java.awt.FlowLayout;import java.awt.event.KeyEvent;import.pdfimport java.awt.FlowLayout;import java.awt.event.KeyEvent;import.pdf
import java.awt.FlowLayout;import java.awt.event.KeyEvent;import.pdf
galagirishp
 
Ejemplos Interfaces Usuario 3
Ejemplos Interfaces Usuario 3Ejemplos Interfaces Usuario 3
Ejemplos Interfaces Usuario 3martha leon
 
How do I make my JTable non editableimport java.awt.; import j.pdf
How do I make my JTable non editableimport java.awt.; import j.pdfHow do I make my JTable non editableimport java.awt.; import j.pdf
How do I make my JTable non editableimport java.awt.; import j.pdf
forwardcom41
 
Advance Java Programs skeleton
Advance Java Programs skeletonAdvance Java Programs skeleton
Advance Java Programs skeleton
Iram Ramrajkar
 
PLEASE HELP ME !!IT IS Due Tonight ;(!i have to submit it before.pdf
PLEASE HELP ME !!IT IS Due Tonight ;(!i have to submit it before.pdfPLEASE HELP ME !!IT IS Due Tonight ;(!i have to submit it before.pdf
PLEASE HELP ME !!IT IS Due Tonight ;(!i have to submit it before.pdf
mohammedfootwear
 
import javaxswing import javaawtevent import javai.pdf
import javaxswing import javaawtevent import javai.pdfimport javaxswing import javaawtevent import javai.pdf
import javaxswing import javaawtevent import javai.pdf
ADITIEYEWEAR
 
I am getting a syntax error. I cant seem to find whats causing t.pdf
I am getting a syntax error. I cant seem to find whats causing t.pdfI am getting a syntax error. I cant seem to find whats causing t.pdf
I am getting a syntax error. I cant seem to find whats causing t.pdf
fashionfolionr
 
package net.codejava.swing.mail;import java.awt.Font;import java.pdf
package net.codejava.swing.mail;import java.awt.Font;import java.pdfpackage net.codejava.swing.mail;import java.awt.Font;import java.pdf
package net.codejava.swing.mail;import java.awt.Font;import java.pdf
sudhirchourasia86
 
code for quiz in my sql
code for quiz  in my sql code for quiz  in my sql
code for quiz in my sql
JOYITAKUNDU1
 
I have done it under neatbeans IDE and just added ToggleGroup for gr.pdf
I have done it under neatbeans IDE and just added ToggleGroup for gr.pdfI have done it under neatbeans IDE and just added ToggleGroup for gr.pdf
I have done it under neatbeans IDE and just added ToggleGroup for gr.pdf
annaimobiles
 

Similar to Chat application in java using swing and socket programming. (20)

Awt
AwtAwt
Awt
 
You are to simulate a dispatcher using a priority queue system in C+.pdf
You are to simulate a dispatcher using a priority queue system in C+.pdfYou are to simulate a dispatcher using a priority queue system in C+.pdf
You are to simulate a dispatcher using a priority queue system in C+.pdf
 
Why following sort does not work (It does not sort last 2 - 3 numbe.pdf
Why following sort does not work (It does not sort last 2 - 3 numbe.pdfWhy following sort does not work (It does not sort last 2 - 3 numbe.pdf
Why following sort does not work (It does not sort last 2 - 3 numbe.pdf
 
Java awt
Java awtJava awt
Java awt
 
CodeZipButtonDemo.javaCodeZipButtonDemo.java Demonstrate a p.docx
CodeZipButtonDemo.javaCodeZipButtonDemo.java Demonstrate a p.docxCodeZipButtonDemo.javaCodeZipButtonDemo.java Demonstrate a p.docx
CodeZipButtonDemo.javaCodeZipButtonDemo.java Demonstrate a p.docx
 
CodeZipButtonDemo.javaCodeZipButtonDemo.java Demonstrate a p.docx
CodeZipButtonDemo.javaCodeZipButtonDemo.java Demonstrate a p.docxCodeZipButtonDemo.javaCodeZipButtonDemo.java Demonstrate a p.docx
CodeZipButtonDemo.javaCodeZipButtonDemo.java Demonstrate a p.docx
 
Program klik sederhana
Program klik sederhanaProgram klik sederhana
Program klik sederhana
 
import java.awt.FlowLayout;import java.awt.event.KeyEvent;import.pdf
import java.awt.FlowLayout;import java.awt.event.KeyEvent;import.pdfimport java.awt.FlowLayout;import java.awt.event.KeyEvent;import.pdf
import java.awt.FlowLayout;import java.awt.event.KeyEvent;import.pdf
 
Ejemplos Interfaces Usuario 3
Ejemplos Interfaces Usuario 3Ejemplos Interfaces Usuario 3
Ejemplos Interfaces Usuario 3
 
How do I make my JTable non editableimport java.awt.; import j.pdf
How do I make my JTable non editableimport java.awt.; import j.pdfHow do I make my JTable non editableimport java.awt.; import j.pdf
How do I make my JTable non editableimport java.awt.; import j.pdf
 
Advance Java Programs skeleton
Advance Java Programs skeletonAdvance Java Programs skeleton
Advance Java Programs skeleton
 
PLEASE HELP ME !!IT IS Due Tonight ;(!i have to submit it before.pdf
PLEASE HELP ME !!IT IS Due Tonight ;(!i have to submit it before.pdfPLEASE HELP ME !!IT IS Due Tonight ;(!i have to submit it before.pdf
PLEASE HELP ME !!IT IS Due Tonight ;(!i have to submit it before.pdf
 
import javaxswing import javaawtevent import javai.pdf
import javaxswing import javaawtevent import javai.pdfimport javaxswing import javaawtevent import javai.pdf
import javaxswing import javaawtevent import javai.pdf
 
Notepad
NotepadNotepad
Notepad
 
Final_Project
Final_ProjectFinal_Project
Final_Project
 
I am getting a syntax error. I cant seem to find whats causing t.pdf
I am getting a syntax error. I cant seem to find whats causing t.pdfI am getting a syntax error. I cant seem to find whats causing t.pdf
I am getting a syntax error. I cant seem to find whats causing t.pdf
 
Easy Button
Easy ButtonEasy Button
Easy Button
 
package net.codejava.swing.mail;import java.awt.Font;import java.pdf
package net.codejava.swing.mail;import java.awt.Font;import java.pdfpackage net.codejava.swing.mail;import java.awt.Font;import java.pdf
package net.codejava.swing.mail;import java.awt.Font;import java.pdf
 
code for quiz in my sql
code for quiz  in my sql code for quiz  in my sql
code for quiz in my sql
 
I have done it under neatbeans IDE and just added ToggleGroup for gr.pdf
I have done it under neatbeans IDE and just added ToggleGroup for gr.pdfI have done it under neatbeans IDE and just added ToggleGroup for gr.pdf
I have done it under neatbeans IDE and just added ToggleGroup for gr.pdf
 

Recently uploaded

Visitor Management System in India- Vizman.app
Visitor Management System in India- Vizman.appVisitor Management System in India- Vizman.app
Visitor Management System in India- Vizman.app
NaapbooksPrivateLimi
 
Developing Distributed High-performance Computing Capabilities of an Open Sci...
Developing Distributed High-performance Computing Capabilities of an Open Sci...Developing Distributed High-performance Computing Capabilities of an Open Sci...
Developing Distributed High-performance Computing Capabilities of an Open Sci...
Globus
 
TROUBLESHOOTING 9 TYPES OF OUTOFMEMORYERROR
TROUBLESHOOTING 9 TYPES OF OUTOFMEMORYERRORTROUBLESHOOTING 9 TYPES OF OUTOFMEMORYERROR
TROUBLESHOOTING 9 TYPES OF OUTOFMEMORYERROR
Tier1 app
 
First Steps with Globus Compute Multi-User Endpoints
First Steps with Globus Compute Multi-User EndpointsFirst Steps with Globus Compute Multi-User Endpoints
First Steps with Globus Compute Multi-User Endpoints
Globus
 
In 2015, I used to write extensions for Joomla, WordPress, phpBB3, etc and I ...
In 2015, I used to write extensions for Joomla, WordPress, phpBB3, etc and I ...In 2015, I used to write extensions for Joomla, WordPress, phpBB3, etc and I ...
In 2015, I used to write extensions for Joomla, WordPress, phpBB3, etc and I ...
Juraj Vysvader
 
How to Position Your Globus Data Portal for Success Ten Good Practices
How to Position Your Globus Data Portal for Success Ten Good PracticesHow to Position Your Globus Data Portal for Success Ten Good Practices
How to Position Your Globus Data Portal for Success Ten Good Practices
Globus
 
Climate Science Flows: Enabling Petabyte-Scale Climate Analysis with the Eart...
Climate Science Flows: Enabling Petabyte-Scale Climate Analysis with the Eart...Climate Science Flows: Enabling Petabyte-Scale Climate Analysis with the Eart...
Climate Science Flows: Enabling Petabyte-Scale Climate Analysis with the Eart...
Globus
 
Advanced Flow Concepts Every Developer Should Know
Advanced Flow Concepts Every Developer Should KnowAdvanced Flow Concepts Every Developer Should Know
Advanced Flow Concepts Every Developer Should Know
Peter Caitens
 
Providing Globus Services to Users of JASMIN for Environmental Data Analysis
Providing Globus Services to Users of JASMIN for Environmental Data AnalysisProviding Globus Services to Users of JASMIN for Environmental Data Analysis
Providing Globus Services to Users of JASMIN for Environmental Data Analysis
Globus
 
Software Testing Exam imp Ques Notes.pdf
Software Testing Exam imp Ques Notes.pdfSoftware Testing Exam imp Ques Notes.pdf
Software Testing Exam imp Ques Notes.pdf
MayankTawar1
 
Exploring Innovations in Data Repository Solutions - Insights from the U.S. G...
Exploring Innovations in Data Repository Solutions - Insights from the U.S. G...Exploring Innovations in Data Repository Solutions - Insights from the U.S. G...
Exploring Innovations in Data Repository Solutions - Insights from the U.S. G...
Globus
 
SOCRadar Research Team: Latest Activities of IntelBroker
SOCRadar Research Team: Latest Activities of IntelBrokerSOCRadar Research Team: Latest Activities of IntelBroker
SOCRadar Research Team: Latest Activities of IntelBroker
SOCRadar
 
Globus Connect Server Deep Dive - GlobusWorld 2024
Globus Connect Server Deep Dive - GlobusWorld 2024Globus Connect Server Deep Dive - GlobusWorld 2024
Globus Connect Server Deep Dive - GlobusWorld 2024
Globus
 
top nidhi software solution freedownload
top nidhi software solution freedownloadtop nidhi software solution freedownload
top nidhi software solution freedownload
vrstrong314
 
2024 RoOUG Security model for the cloud.pptx
2024 RoOUG Security model for the cloud.pptx2024 RoOUG Security model for the cloud.pptx
2024 RoOUG Security model for the cloud.pptx
Georgi Kodinov
 
A Comprehensive Look at Generative AI in Retail App Testing.pdf
A Comprehensive Look at Generative AI in Retail App Testing.pdfA Comprehensive Look at Generative AI in Retail App Testing.pdf
A Comprehensive Look at Generative AI in Retail App Testing.pdf
kalichargn70th171
 
Beyond Event Sourcing - Embracing CRUD for Wix Platform - Java.IL
Beyond Event Sourcing - Embracing CRUD for Wix Platform - Java.ILBeyond Event Sourcing - Embracing CRUD for Wix Platform - Java.IL
Beyond Event Sourcing - Embracing CRUD for Wix Platform - Java.IL
Natan Silnitsky
 
Globus Compute wth IRI Workflows - GlobusWorld 2024
Globus Compute wth IRI Workflows - GlobusWorld 2024Globus Compute wth IRI Workflows - GlobusWorld 2024
Globus Compute wth IRI Workflows - GlobusWorld 2024
Globus
 
How Recreation Management Software Can Streamline Your Operations.pptx
How Recreation Management Software Can Streamline Your Operations.pptxHow Recreation Management Software Can Streamline Your Operations.pptx
How Recreation Management Software Can Streamline Your Operations.pptx
wottaspaceseo
 
Quarkus Hidden and Forbidden Extensions
Quarkus Hidden and Forbidden ExtensionsQuarkus Hidden and Forbidden Extensions
Quarkus Hidden and Forbidden Extensions
Max Andersen
 

Recently uploaded (20)

Visitor Management System in India- Vizman.app
Visitor Management System in India- Vizman.appVisitor Management System in India- Vizman.app
Visitor Management System in India- Vizman.app
 
Developing Distributed High-performance Computing Capabilities of an Open Sci...
Developing Distributed High-performance Computing Capabilities of an Open Sci...Developing Distributed High-performance Computing Capabilities of an Open Sci...
Developing Distributed High-performance Computing Capabilities of an Open Sci...
 
TROUBLESHOOTING 9 TYPES OF OUTOFMEMORYERROR
TROUBLESHOOTING 9 TYPES OF OUTOFMEMORYERRORTROUBLESHOOTING 9 TYPES OF OUTOFMEMORYERROR
TROUBLESHOOTING 9 TYPES OF OUTOFMEMORYERROR
 
First Steps with Globus Compute Multi-User Endpoints
First Steps with Globus Compute Multi-User EndpointsFirst Steps with Globus Compute Multi-User Endpoints
First Steps with Globus Compute Multi-User Endpoints
 
In 2015, I used to write extensions for Joomla, WordPress, phpBB3, etc and I ...
In 2015, I used to write extensions for Joomla, WordPress, phpBB3, etc and I ...In 2015, I used to write extensions for Joomla, WordPress, phpBB3, etc and I ...
In 2015, I used to write extensions for Joomla, WordPress, phpBB3, etc and I ...
 
How to Position Your Globus Data Portal for Success Ten Good Practices
How to Position Your Globus Data Portal for Success Ten Good PracticesHow to Position Your Globus Data Portal for Success Ten Good Practices
How to Position Your Globus Data Portal for Success Ten Good Practices
 
Climate Science Flows: Enabling Petabyte-Scale Climate Analysis with the Eart...
Climate Science Flows: Enabling Petabyte-Scale Climate Analysis with the Eart...Climate Science Flows: Enabling Petabyte-Scale Climate Analysis with the Eart...
Climate Science Flows: Enabling Petabyte-Scale Climate Analysis with the Eart...
 
Advanced Flow Concepts Every Developer Should Know
Advanced Flow Concepts Every Developer Should KnowAdvanced Flow Concepts Every Developer Should Know
Advanced Flow Concepts Every Developer Should Know
 
Providing Globus Services to Users of JASMIN for Environmental Data Analysis
Providing Globus Services to Users of JASMIN for Environmental Data AnalysisProviding Globus Services to Users of JASMIN for Environmental Data Analysis
Providing Globus Services to Users of JASMIN for Environmental Data Analysis
 
Software Testing Exam imp Ques Notes.pdf
Software Testing Exam imp Ques Notes.pdfSoftware Testing Exam imp Ques Notes.pdf
Software Testing Exam imp Ques Notes.pdf
 
Exploring Innovations in Data Repository Solutions - Insights from the U.S. G...
Exploring Innovations in Data Repository Solutions - Insights from the U.S. G...Exploring Innovations in Data Repository Solutions - Insights from the U.S. G...
Exploring Innovations in Data Repository Solutions - Insights from the U.S. G...
 
SOCRadar Research Team: Latest Activities of IntelBroker
SOCRadar Research Team: Latest Activities of IntelBrokerSOCRadar Research Team: Latest Activities of IntelBroker
SOCRadar Research Team: Latest Activities of IntelBroker
 
Globus Connect Server Deep Dive - GlobusWorld 2024
Globus Connect Server Deep Dive - GlobusWorld 2024Globus Connect Server Deep Dive - GlobusWorld 2024
Globus Connect Server Deep Dive - GlobusWorld 2024
 
top nidhi software solution freedownload
top nidhi software solution freedownloadtop nidhi software solution freedownload
top nidhi software solution freedownload
 
2024 RoOUG Security model for the cloud.pptx
2024 RoOUG Security model for the cloud.pptx2024 RoOUG Security model for the cloud.pptx
2024 RoOUG Security model for the cloud.pptx
 
A Comprehensive Look at Generative AI in Retail App Testing.pdf
A Comprehensive Look at Generative AI in Retail App Testing.pdfA Comprehensive Look at Generative AI in Retail App Testing.pdf
A Comprehensive Look at Generative AI in Retail App Testing.pdf
 
Beyond Event Sourcing - Embracing CRUD for Wix Platform - Java.IL
Beyond Event Sourcing - Embracing CRUD for Wix Platform - Java.ILBeyond Event Sourcing - Embracing CRUD for Wix Platform - Java.IL
Beyond Event Sourcing - Embracing CRUD for Wix Platform - Java.IL
 
Globus Compute wth IRI Workflows - GlobusWorld 2024
Globus Compute wth IRI Workflows - GlobusWorld 2024Globus Compute wth IRI Workflows - GlobusWorld 2024
Globus Compute wth IRI Workflows - GlobusWorld 2024
 
How Recreation Management Software Can Streamline Your Operations.pptx
How Recreation Management Software Can Streamline Your Operations.pptxHow Recreation Management Software Can Streamline Your Operations.pptx
How Recreation Management Software Can Streamline Your Operations.pptx
 
Quarkus Hidden and Forbidden Extensions
Quarkus Hidden and Forbidden ExtensionsQuarkus Hidden and Forbidden Extensions
Quarkus Hidden and Forbidden Extensions
 

Chat application in java using swing and socket programming.

  • 1. Firstly run myserver.java then run login.java //Login page import javax.swing.*; import java.awt.*; import java.awt.event.*; import java.io.*; 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; JButton button; JLabel heading; JLabel label; public static void main(String[] args){ new Login(); } public Login(){ frame1 = new JFrame("Login Page"); tf=new JTextField(); button=new JButton("Login"); heading=new JLabel("Chat Server");
  • 2. heading.setFont(new Font("Impact", Font.BOLD,40)); label=new JLabel("Enter you Login Name"); label.setFont(new Font("Serif", Font.PLAIN, 24)); JPanel panel = new JPanel(); button.addActionListener(this); panel.add(heading);panel.add(tf);panel.add(label); panel.add(button); heading.setBounds(30,20,280,80); label.setBounds(20,100,250,60); tf.setBounds(50,150,150,30); button.setBounds(70,200,90,30); frame1.add(panel); panel.setLayout(null); frame1.setSize(300, 300); frame1.setVisible(true); frame1.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); } // pass the user name to MyClient class public void actionPerformed(ActionEvent e){ String name=""; try{ name=tf.getText(); frame1.dispose(); MyClient mc=new MyClient(name);
  • 3. //MyServer ms=new MyServer(); }catch (IOException te){} } } //MyServer.java 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();
  • 4. 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){}
  • 5. } } //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);
  • 6. 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());
  • 7. 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;
  • 8. 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();
  • 9. Socket st; while(i.hasNext()){ st=(Socket)i.next(); dout=new DataOutputStream(st.getOutputStream()); dout.writeUTF(str); dout.flush(); } } } //MyClient.java 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;
  • 10. JList list1; JTextArea tf; DefaultListModel model; DefaultListModel model1; JButton button; JButton lout; JScrollPane scrollpane; JScrollPane scrollpane1; JLabel label,label2,label3; Socket s,s1,s2; DataInputStream din; DataOutputStream dout; DataOutputStream dlout; DataOutputStream dout1; DataInputStream din1; String name; MyClient(String name)throws IOException{ frame = new JFrame("Chat Window"); frame.setLocation(375,100); tf=new JTextArea(); model=new DefaultListModel(); model1=new DefaultListModel(); label=new JLabel("Message");
  • 11. label2=new JLabel("Onilne Users"); label3=new JLabel("Chatting Messages"); list=new JList(model); list1=new JList(model1); button=new JButton("Send"); lout=new JButton("Back"); scrollpane=new JScrollPane(list); scrollpane1=new JScrollPane(list1); //from here scrollpane.getVerticalScrollBar().addAdjustmentListener(new AdjustmentListener() { public void adjustmentValueChanged(AdjustmentEvent e) { e.getAdjustable().setValue(e.getAdjustable().getMaximum()); } }); scrollpane1.getVerticalScrollBar().addAdjustmentListener(new AdjustmentListener() { public void adjustmentValueChanged(AdjustmentEvent e) { e.getAdjustable().setValue(e.getAdjustable().getMaximum()); } });
  • 12. //try JPanel panel = new JPanel(); button.addActionListener(this); lout.addActionListener(this); panel.add(tf);panel.add(button);panel.add(scrollpane); panel.add(label);panel.add(label2);panel.add(label3);panel.add(lout); panel.add(scrollpane1); scrollpane.setBounds(10,40,250,300); scrollpane1.setBounds(350,40,150,300); label.setBounds(10,350,80,30); label2.setBounds(350,20,150,20); label3.setBounds(10,20,250,20); tf.setBounds(10,380,380,70); button.setBounds(410,380,90,30); lout.setBounds(410,420,90,30); frame.add(panel); panel.setLayout(null); frame.setSize(550,500); frame.setResizable(false); frame.setVisible(true); frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); this.name=name; frame.addWindowListener(this); s=new Socket("localhost",1004); //creates a socket object
  • 13. 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){
  • 14. 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(); //new Welcome(); JOptionPane.showMessageDialog(null,"Return Back to Welcome page"); 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){} }
  • 15. } 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;
  • 16. 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
  • 17. 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){} } } }