Saturday, January 29, 2011

Tcp Echo (Client - Server)

//Client

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

class client
{
    public static void main(String[] arr) throws Exception
    {
        BufferedReader br=null;
        PrintWriter pw=null;
        Scanner input=null;
        Socket cs;

        cs = new Socket("localhost",1987);
        input = new Scanner(System.in);
        br = new BufferedReader(new InputStreamReader(cs.getInputStream()));
        pw = new PrintWriter(cs.getOutputStream(),true);

        System.out.print("enter data : ");
        String str=input.nextLine();

        pw.println(str);

        System.out.println("Data from Server : " + br.readLine());
    }
}

//Server


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

class myserver implements Runnable
{
    Socket cs;
    Thread t;
    BufferedReader br = null;
    PrintWriter pw = null;

    myserver(Socket cs)
    {
        this.cs=cs;
        t = new Thread(this);
        t.start();
    }
   
    public void run()
    {
        while(true)
        {
            try
            {
                br = new BufferedReader(new InputStreamReader(cs.getInputStream()));
                pw = new PrintWriter(cs.getOutputStream(),true);
                pw.println(br.readLine());
            }
            catch(IOException ie){}
        }
    }

}

class server
{
    public static void main(String[] arr)
    {
        ServerSocket ss;
        try
        {
            ss = new ServerSocket(1987);

            while(true)
            {
                Socket cs=ss.accept();
                new myserver(cs);
            }
        }
        catch(IOException ie){}
    }
}

No comments:

Post a Comment

Disqus for yogi's talk

comments powered by Disqus