Write program in which server listens on port for incoming connection from client program. When server connects to a client it reads one line of text from client, reverse chars in a line and sends them back to the client. - Tips N TRIKS

Saturday 5 August 2017

Write program in which server listens on port for incoming connection from client program. When server connects to a client it reads one line of text from client, reverse chars in a line and sends them back to the client.

Source Code:
Client side:
import java.io.*;
import java.net.*;
import java.util.*;
class tcpclient
{
      public static void main(String args[]) throws Exception
      {
                  Scanner sc=new Scanner(System.in);
                  System.out.println("Enter Port:");
                  int port=sc.nextInt();                                
                  Socket soc=new Socket(InetAddress.getLocalHost(),port);
                  InputStream in=soc.getInputStream();
                  OutputStream out=soc.getOutputStream();            
                  System.out.println("Give your data:");
                  String str;
                  str=sc.next();                      
                  byte buf[]=str.getBytes();
                  out.write(buf);                   
                  int c;
                  str="";
                  byte buff[]=new byte[100];
                  c=in.read(buff);
                  for(int i=0;i<c;i++)
                              str = str+(char)buff[i];
                  System.out.print("Reverse string received from server is : "+str);                     
      }
}

Server side
import java.net.*;
import java.io.*;
import java.util.*;
class tcpserver
{
      public static void main(String args[]) throws IOException
      {
                  Scanner sc=new Scanner(System.in);             
                  System.out.println("Enter Port:");
                  int port=sc.nextInt();                    
                  ServerSocket ss=new ServerSocket(port);
                  System.out.println("Waiting for Client...");
                  Socket soc=ss.accept();               
                  InputStream in=soc.getInputStream();
                  OutputStream out=soc.getOutputStream();            
                  String str = " ";
                  byte buf[]=new byte[100];
                  int n=in.read(buf);
                  for(int i=0;i<n;i++)
                              str = str+(char)buf[i];
                  System.out.println("Received: "+str);             
                  String str1 = " ";
                  for(int i = str.length()-1;i>=0;i--)
                              str1 = str1+str.charAt(i);
                  byte buff[] = str1.getBytes();
                  System.out.println("Writing to client");
                  out.write(buff);
      }
}  


Output:


    

No comments:

Post a Comment