SlideShare a Scribd company logo
1 of 17
Download to read offline
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

What's hot (20)

MULTI THREADING IN JAVA
MULTI THREADING IN JAVAMULTI THREADING IN JAVA
MULTI THREADING IN JAVA
 
NestJS - O framework progressivo
NestJS - O framework progressivoNestJS - O framework progressivo
NestJS - O framework progressivo
 
Collection Framework in java
Collection Framework in javaCollection Framework in java
Collection Framework in java
 
jQuery
jQueryjQuery
jQuery
 
Android Threading
Android ThreadingAndroid Threading
Android Threading
 
Collections In Java
Collections In JavaCollections In Java
Collections In Java
 
JDBC ppt
JDBC pptJDBC ppt
JDBC ppt
 
Java Collections
Java  Collections Java  Collections
Java Collections
 
Java constructors
Java constructorsJava constructors
Java constructors
 
jQuery from the very beginning
jQuery from the very beginningjQuery from the very beginning
jQuery from the very beginning
 
[Final] ReactJS presentation
[Final] ReactJS presentation[Final] ReactJS presentation
[Final] ReactJS presentation
 
JDBC: java DataBase connectivity
JDBC: java DataBase connectivityJDBC: java DataBase connectivity
JDBC: java DataBase connectivity
 
Advance Java Topics (J2EE)
Advance Java Topics (J2EE)Advance Java Topics (J2EE)
Advance Java Topics (J2EE)
 
Broadcast Receiver
Broadcast ReceiverBroadcast Receiver
Broadcast Receiver
 
Notification android
Notification androidNotification android
Notification android
 
Event handling
Event handlingEvent handling
Event handling
 
CSharp Presentation
CSharp PresentationCSharp Presentation
CSharp Presentation
 
Android studio installation
Android studio installationAndroid studio installation
Android studio installation
 
Java swing
Java swingJava swing
Java swing
 
Labels and buttons
Labels and buttonsLabels and buttons
Labels and buttons
 

Similar to Run Java Login and Chat Server Code

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+.pdfJUSTSTYLISH3B2MOHALI
 
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.pdfgopalk44
 
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.docxmary772
 
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.docxmccormicknadine86
 
Program klik sederhana
Program klik sederhanaProgram klik sederhana
Program klik sederhanaHenfry 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.pdfgalagirishp
 
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.pdfforwardcom41
 
Advance Java Programs skeleton
Advance Java Programs skeletonAdvance Java Programs skeleton
Advance Java Programs skeletonIram 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.pdfmohammedfootwear
 
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.pdfADITIEYEWEAR
 
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.pdffashionfolionr
 
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.pdfsudhirchourasia86
 
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.pdfannaimobiles
 

Similar to Run Java Login and Chat Server Code (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

EY_Graph Database Powered Sustainability
EY_Graph Database Powered SustainabilityEY_Graph Database Powered Sustainability
EY_Graph Database Powered SustainabilityNeo4j
 
Best Web Development Agency- Idiosys USA.pdf
Best Web Development Agency- Idiosys USA.pdfBest Web Development Agency- Idiosys USA.pdf
Best Web Development Agency- Idiosys USA.pdfIdiosysTechnologies1
 
A healthy diet for your Java application Devoxx France.pdf
A healthy diet for your Java application Devoxx France.pdfA healthy diet for your Java application Devoxx France.pdf
A healthy diet for your Java application Devoxx France.pdfMarharyta Nedzelska
 
Maximizing Efficiency and Profitability with OnePlan’s Professional Service A...
Maximizing Efficiency and Profitability with OnePlan’s Professional Service A...Maximizing Efficiency and Profitability with OnePlan’s Professional Service A...
Maximizing Efficiency and Profitability with OnePlan’s Professional Service A...OnePlan Solutions
 
Introduction Computer Science - Software Design.pdf
Introduction Computer Science - Software Design.pdfIntroduction Computer Science - Software Design.pdf
Introduction Computer Science - Software Design.pdfFerryKemperman
 
Implementing Zero Trust strategy with Azure
Implementing Zero Trust strategy with AzureImplementing Zero Trust strategy with Azure
Implementing Zero Trust strategy with AzureDinusha Kumarasiri
 
PREDICTING RIVER WATER QUALITY ppt presentation
PREDICTING  RIVER  WATER QUALITY  ppt presentationPREDICTING  RIVER  WATER QUALITY  ppt presentation
PREDICTING RIVER WATER QUALITY ppt presentationvaddepallysandeep122
 
KnowAPIs-UnknownPerf-jaxMainz-2024 (1).pptx
KnowAPIs-UnknownPerf-jaxMainz-2024 (1).pptxKnowAPIs-UnknownPerf-jaxMainz-2024 (1).pptx
KnowAPIs-UnknownPerf-jaxMainz-2024 (1).pptxTier1 app
 
SuccessFactors 1H 2024 Release - Sneak-Peek by Deloitte Germany
SuccessFactors 1H 2024 Release - Sneak-Peek by Deloitte GermanySuccessFactors 1H 2024 Release - Sneak-Peek by Deloitte Germany
SuccessFactors 1H 2024 Release - Sneak-Peek by Deloitte GermanyChristoph Pohl
 
Ahmed Motair CV April 2024 (Senior SW Developer)
Ahmed Motair CV April 2024 (Senior SW Developer)Ahmed Motair CV April 2024 (Senior SW Developer)
Ahmed Motair CV April 2024 (Senior SW Developer)Ahmed Mater
 
Call Us🔝>༒+91-9711147426⇛Call In girls karol bagh (Delhi)
Call Us🔝>༒+91-9711147426⇛Call In girls karol bagh (Delhi)Call Us🔝>༒+91-9711147426⇛Call In girls karol bagh (Delhi)
Call Us🔝>༒+91-9711147426⇛Call In girls karol bagh (Delhi)jennyeacort
 
Alluxio Monthly Webinar | Cloud-Native Model Training on Distributed Data
Alluxio Monthly Webinar | Cloud-Native Model Training on Distributed DataAlluxio Monthly Webinar | Cloud-Native Model Training on Distributed Data
Alluxio Monthly Webinar | Cloud-Native Model Training on Distributed DataAlluxio, Inc.
 
Building a General PDE Solving Framework with Symbolic-Numeric Scientific Mac...
Building a General PDE Solving Framework with Symbolic-Numeric Scientific Mac...Building a General PDE Solving Framework with Symbolic-Numeric Scientific Mac...
Building a General PDE Solving Framework with Symbolic-Numeric Scientific Mac...stazi3110
 
Cyber security and its impact on E commerce
Cyber security and its impact on E commerceCyber security and its impact on E commerce
Cyber security and its impact on E commercemanigoyal112
 
GOING AOT WITH GRAALVM – DEVOXX GREECE.pdf
GOING AOT WITH GRAALVM – DEVOXX GREECE.pdfGOING AOT WITH GRAALVM – DEVOXX GREECE.pdf
GOING AOT WITH GRAALVM – DEVOXX GREECE.pdfAlina Yurenko
 
React Server Component in Next.js by Hanief Utama
React Server Component in Next.js by Hanief UtamaReact Server Component in Next.js by Hanief Utama
React Server Component in Next.js by Hanief UtamaHanief Utama
 
What are the key points to focus on before starting to learn ETL Development....
What are the key points to focus on before starting to learn ETL Development....What are the key points to focus on before starting to learn ETL Development....
What are the key points to focus on before starting to learn ETL Development....kzayra69
 
Taming Distributed Systems: Key Insights from Wix's Large-Scale Experience - ...
Taming Distributed Systems: Key Insights from Wix's Large-Scale Experience - ...Taming Distributed Systems: Key Insights from Wix's Large-Scale Experience - ...
Taming Distributed Systems: Key Insights from Wix's Large-Scale Experience - ...Natan Silnitsky
 

Recently uploaded (20)

EY_Graph Database Powered Sustainability
EY_Graph Database Powered SustainabilityEY_Graph Database Powered Sustainability
EY_Graph Database Powered Sustainability
 
Hot Sexy call girls in Patel Nagar🔝 9953056974 🔝 escort Service
Hot Sexy call girls in Patel Nagar🔝 9953056974 🔝 escort ServiceHot Sexy call girls in Patel Nagar🔝 9953056974 🔝 escort Service
Hot Sexy call girls in Patel Nagar🔝 9953056974 🔝 escort Service
 
Best Web Development Agency- Idiosys USA.pdf
Best Web Development Agency- Idiosys USA.pdfBest Web Development Agency- Idiosys USA.pdf
Best Web Development Agency- Idiosys USA.pdf
 
A healthy diet for your Java application Devoxx France.pdf
A healthy diet for your Java application Devoxx France.pdfA healthy diet for your Java application Devoxx France.pdf
A healthy diet for your Java application Devoxx France.pdf
 
Maximizing Efficiency and Profitability with OnePlan’s Professional Service A...
Maximizing Efficiency and Profitability with OnePlan’s Professional Service A...Maximizing Efficiency and Profitability with OnePlan’s Professional Service A...
Maximizing Efficiency and Profitability with OnePlan’s Professional Service A...
 
Introduction Computer Science - Software Design.pdf
Introduction Computer Science - Software Design.pdfIntroduction Computer Science - Software Design.pdf
Introduction Computer Science - Software Design.pdf
 
Implementing Zero Trust strategy with Azure
Implementing Zero Trust strategy with AzureImplementing Zero Trust strategy with Azure
Implementing Zero Trust strategy with Azure
 
PREDICTING RIVER WATER QUALITY ppt presentation
PREDICTING  RIVER  WATER QUALITY  ppt presentationPREDICTING  RIVER  WATER QUALITY  ppt presentation
PREDICTING RIVER WATER QUALITY ppt presentation
 
Advantages of Odoo ERP 17 for Your Business
Advantages of Odoo ERP 17 for Your BusinessAdvantages of Odoo ERP 17 for Your Business
Advantages of Odoo ERP 17 for Your Business
 
KnowAPIs-UnknownPerf-jaxMainz-2024 (1).pptx
KnowAPIs-UnknownPerf-jaxMainz-2024 (1).pptxKnowAPIs-UnknownPerf-jaxMainz-2024 (1).pptx
KnowAPIs-UnknownPerf-jaxMainz-2024 (1).pptx
 
SuccessFactors 1H 2024 Release - Sneak-Peek by Deloitte Germany
SuccessFactors 1H 2024 Release - Sneak-Peek by Deloitte GermanySuccessFactors 1H 2024 Release - Sneak-Peek by Deloitte Germany
SuccessFactors 1H 2024 Release - Sneak-Peek by Deloitte Germany
 
Ahmed Motair CV April 2024 (Senior SW Developer)
Ahmed Motair CV April 2024 (Senior SW Developer)Ahmed Motair CV April 2024 (Senior SW Developer)
Ahmed Motair CV April 2024 (Senior SW Developer)
 
Call Us🔝>༒+91-9711147426⇛Call In girls karol bagh (Delhi)
Call Us🔝>༒+91-9711147426⇛Call In girls karol bagh (Delhi)Call Us🔝>༒+91-9711147426⇛Call In girls karol bagh (Delhi)
Call Us🔝>༒+91-9711147426⇛Call In girls karol bagh (Delhi)
 
Alluxio Monthly Webinar | Cloud-Native Model Training on Distributed Data
Alluxio Monthly Webinar | Cloud-Native Model Training on Distributed DataAlluxio Monthly Webinar | Cloud-Native Model Training on Distributed Data
Alluxio Monthly Webinar | Cloud-Native Model Training on Distributed Data
 
Building a General PDE Solving Framework with Symbolic-Numeric Scientific Mac...
Building a General PDE Solving Framework with Symbolic-Numeric Scientific Mac...Building a General PDE Solving Framework with Symbolic-Numeric Scientific Mac...
Building a General PDE Solving Framework with Symbolic-Numeric Scientific Mac...
 
Cyber security and its impact on E commerce
Cyber security and its impact on E commerceCyber security and its impact on E commerce
Cyber security and its impact on E commerce
 
GOING AOT WITH GRAALVM – DEVOXX GREECE.pdf
GOING AOT WITH GRAALVM – DEVOXX GREECE.pdfGOING AOT WITH GRAALVM – DEVOXX GREECE.pdf
GOING AOT WITH GRAALVM – DEVOXX GREECE.pdf
 
React Server Component in Next.js by Hanief Utama
React Server Component in Next.js by Hanief UtamaReact Server Component in Next.js by Hanief Utama
React Server Component in Next.js by Hanief Utama
 
What are the key points to focus on before starting to learn ETL Development....
What are the key points to focus on before starting to learn ETL Development....What are the key points to focus on before starting to learn ETL Development....
What are the key points to focus on before starting to learn ETL Development....
 
Taming Distributed Systems: Key Insights from Wix's Large-Scale Experience - ...
Taming Distributed Systems: Key Insights from Wix's Large-Scale Experience - ...Taming Distributed Systems: Key Insights from Wix's Large-Scale Experience - ...
Taming Distributed Systems: Key Insights from Wix's Large-Scale Experience - ...
 

Run Java Login and Chat Server Code

  • 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){} } } }