Tuesday, March 4, 2014

Simple program to chat with two computers !




Server.java :


import java.net.*;
import java.io.*;
import java.util.*;
class hh extends Thread
{
 Socket s;
 hh(Socket ss)
 {
 s=ss;
 }
 public void run()
 {
 try
 {
 DataInputStream din= new DataInputStream(s.getInputStream());
 String msg;

 msg=din.readUTF();
 System.out.println(msg);
 }
 catch(Exception e)
 {
 }

 }

}


class server
{
     public static void main(String args[])
   
          {try
  {
          ServerSocket s1=new ServerSocket(1800);
          Socket s=s1.accept();
                   DataOutputStream dos=new DataOutputStream(s.getOutputStream());
                   BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
        // dos.writeUTF("Hello this is server!!");
        String msg;
          hh obj=new hh(s);
          Thread th =new Thread(obj);
          th.start();
          System.out.println("Enter your name");
          String name=br.readLine();
while(true)
{
msg=br.readLine();
dos.writeUTF(name+" : "+ msg);
}
  }
catch(Exception e)
{
   System.out.println("OOPS !!");
}
}
}



Here is the client side code !


client.java

import java.net.*;
import java.io.*;
import java.util.*;
class hh extends Thread
{
 Socket s;
 hh(Socket ss)
 {
 s=ss;
 }
 public void run()
 {
   try
 {
 DataInputStream din= new DataInputStream(s.getInputStream());
 String msg;
 while(true)
 {
 msg=din.readUTF();
 System.out.println(msg);
 }
 }
 catch(Exception e)
 {
 }

 }

}
class client
{

     public static void main(String args[])
   
          {
         
       

         
         
          try
  {
          Socket s1=new Socket("localhost",1800);
          BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
          DataOutputStream dos=new DataOutputStream(s1.getOutputStream());
         // dos.writeUTF("Hi this is client!!");
         
          String msg;
          hh obj=new hh(s1);
          Thread th =new Thread(obj);
          obj.start();
          System.out.println("Enter your name");
          String name=br.readLine();
while(true)
{
msg=br.readLine();
dos.writeUTF(name+" : "+msg);
}
        
         }

catch(Exception e)
{
   System.out.println("OOPS Client is OFF !!");
}
}
}


No comments:

Post a Comment