Socket Programming for sorting array

Server-Client Socket Program For Sorting Elements

In this post, I had shared a program related to the socket programming in which the sorting of the elements of array can be done.

In this code there should be two file namely server.java and client.java. In client.java code is created to take the size of the array and elements of array and it send to the server. In server.java the value of the size of array and elements of array is used for sorting the elements and sends back to the client.

Let review the code for the above aim.


Client.java

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

public class ClientSort {

    public static void main(String args[]) throws Exception{
     
        Socket s=new Socket("localhost",1212);
        int n,i;
        DataOutputStream out=new DataOutputStream(s.getOutputStream());
        DataInputStream in=new DataInputStream(System.in);
        Scanner sc=new Scanner(System.in);
        System.out.println("Enter the Size of array: ");
        n=sc.nextInt();
        int a[]=new int[n];
        out.writeInt(n);
        for(i=0;i<n;i++)
        {
            System.out.println("Enter a[" +(i+1) +"]:" );
            a[i]=sc.nextInt();
            out.writeInt(a[i]);
        }

        for(i=0;i<n;i++)
        {
            a[i]=in.readInt();
            out.writeInt(a[i]);
        }

    }
}


Server.java

package sorting_with_server;
import java.io.*;
import java.net.*;

public class ServerSort {
    public static void main(String[] args)throws IOException {
            ServerSocket ss=new ServerSocket(1212);
            Socket s=ss.accept();
            int n,i,j,key,temp;
            DataOutputStream out=new DataOutputStream(s.getOutputStream());
            DataInputStream in=new DataInputStream(s.getInputStream());
            n=in.readInt();
            int a[]=new int[n+1];
            for(i=0;i<n;i++)
            {
              a[i]=in.readInt();
            }

            for(i=1;i<=n;i++)
            {
                key=i;
                for(j=0;j<i;j++)
                {
                    if(a[j]>a[key])
                    {
                        key=a[j];
                        a[j]=a[j+1];
                        a[j+1]=key;
                    }
                }
            }

          for(i=0;i<n;i++)
          {
            out.writeInt(a[i]);
          }

    }

}

Happy Coding :)

Comments

Popular posts from this blog

MultiSelection of Item in Recycler View

Upload Image From Android To Php Server

Merge Sort