TCP Protocol | Data Communication and Networking | Example


 Client

import java.net.* ;

import java.io.* ;

import java.util.*;

public class Q1_Client{

    public static void main(String [] args)

    {

        try {

            Scanner scan=new Scanner(System.in);

            Socket skt= new Socket("localhost",0722);

            InputStream in = skt.getInputStream();

            OutputStream out = skt.getOutputStream();

            byte[] sdata=new byte[1024];

            byte[] rdata=new byte[1024];

            System.out.println("\nEnter Number: ");

            int st=scan.nextInt();

            String s=String.valueOf(st);

            sdata=s.getBytes();

            out.write(sdata);

            in.read(rdata);

            String msg=new String(rdata);

            System.out.println("\nSquare of "+st+" is: "+msg);

            out.close();

            skt.close();

            scan.close();

        } catch (Exception e) {

            System.out.println("Didn't get any Data....");

        }

    }

}

Server

import java.net.* ;

import java.io.* ;

import java.util.*;

public class Q1_Server{

    public static void main(String[] args)throws Exception {

        ServerSocket srvr=new ServerSocket(0722);

        Socket skt=srvr.accept();

        System.out.println("\nServer is connected!!");

        OutputStream out = skt.getOutputStream();

        InputStream in = skt.getInputStream();

        byte buf[]=new byte[50];

        in.read(buf);

        String msg=new String(buf);

        int m=Integer.parseInt(msg.trim());

        m=m*m;

        System.out.println("\nSending Data: "+m);

        msg=String.valueOf(m);

        out.write(msg.getBytes());

        in.close();

        //srvr.close();

    }

}

Output


request a number from client side and server will calculate the square of the number and return it to client in response use tcp protocol implementation,tcp protocol,data communication and networking


request a number from client side and server will calculate the square of the number and return it to client in response use tcp protocol implementation,tcp protocol,data communication and networking

String operations in Java

UDP Protocol

Comment your views on this Article :)


Thank you for visiting my blog :)


No comments

Comment your views on this article

Powered by Blogger.