Tuesday, 2 October 2012

Java program for Public Chat

AIM
Write a program for implement Public chat using JAVA

PROGRAM

//publicchatC.java

import java.io.*;
import java.net.*;
import java.awt.*;
import java.awt.event.*;
public class publicchatC extends Frame implements ActionListener
{
TextArea txt1,txt2;
Button btn;
String msg;
PrintWriter pw;
Socket s;
public publicchatC()
{
   setLayout(new GridLayout(3,1));
   txt1=new TextArea();
   btn=new Button("Send");
   txt2=new TextArea();
   add(txt1);
   add(btn);
   add(txt2);
   txt1.setText("");
   txt2.setText("");
   btn.addActionListener(this);
   addWindowListener(new WindowAdapter()
   {
      public void WindowClosing(WindowEvent e)
      {
       setVisible(false);
      } 
  
   });

}

public void setConnection()
{

   try
   {
      s=new Socket("localhost",6969);
      BufferedReader br=new BufferedReader(new InputStreamReader(s.getInputStream()));
      pw=new PrintWriter(s.getOutputStream());
      while(true)
      {
      
         msg=br.readLine();
         txt2.append("Rec:"+msg+"\n");
       
      
      }
    }
   catch(Exception e)
   {
    System.out.println(e);
   
   }

}

public void actionPerformed(ActionEvent ae)
{
  try
  {
  
      
     if(ae.getSource()==btn)
     {
      msg=txt1.getText();
      txt2.append("Send:"+msg+"\n");
      pw.println(msg);
      pw.flush();
     }
   }
 
   catch(Exception e)
   {
    System.out.println(e);
   
   } 

}


public static void main(String args[])throws Exception
{
  publicchatC obj=new publicchatC();
  obj.setSize(300,300);
  obj.setVisible(true);
  obj.setConnection();

}
}



------------------------------------------------------------------------
//publicchatS.java


import java.io.*;
import java.net.*;
import java.awt.*;
import java.awt.event.*;
class publicchatS implements Runnable
{
ServerSocket ss;
Socket s[]=new Socket[10];
String msg1,msg2;
PrintWriter pw;
Thread t[]=new Thread[10];
BufferedReader br;
int i,k;
public publicchatS()
{
  try
  {
  ss=new ServerSocket(6969);
  for(i=0;i<3;i++)
  s[i]=ss.accept();
  }
  catch(Exception e)
  {
  System.out.println(e);
  }
  
}

public void run()
{
  try
  {
  while(true)
  {
    for(int j=0;j<i;j++)
    {
     if(Thread.currentThread()==t[j])
     {

      System.out.println("C Thread:"+Thread.currentThread());
      br=new BufferedReader(new InputStreamReader(s[j].getInputStream()));
      msg1=br.readLine();
      System.out.println("Rec:"+msg1);
      k=j;
      }
      }
  for(int p=0;p<i;p++)
  {
   if(p!=k)
   {
   pw=new PrintWriter(s[p].getOutputStream(),true);
   pw.println(msg1);
   pw.flush();
   }}
 }}
 catch(Exception e)
 {
 System.out.println(e);
 }
}

public static void main(String msg[])throws Exception
{
publicchatS obj=new publicchatS();
for(int i=0;i<3;i++)
obj.t[i]=new Thread(obj);
for(int i=0;i<3;i++)
obj.t[i].start();

}

}

No comments:

Post a Comment