Sunday, February 2, 2014

A Simple Server Client Application in Java

A Simple Server Client Application in java using TCP Connection




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

public class TCPClient
    {
        public static void main(String[] arg) throws Exception
        {
            String sentence;
            String modifiedSentence;
            BufferedReader inFromUser=new BufferedReader(new InputStreamReader(System.in));
            Socket clientSocket=new Socket("localhost",6789);
            DataOutputStream outToServer=new DataOutputStream(clientSocket.getOutputStream());
            BufferedReader inFromServer=new BufferedReader(new InputStreamReader(clientSocket.getInputStream()) );
            sentence=inFromUser.readLine();
            outToServer.writeBytes(sentence + '\n');
            modifiedSentence=inFromServer.readLine();
            System.out.println("From Server: "+modifiedSentence);
            clientSocket.close();
        }
    }



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

class TCPServer
    {
        public static void main(String[] arg) throws Exception
        {
            String clientSentence;
            String capitalizedSentence;
            ServerSocket welcomeSocket=new ServerSocket(6789);
           
            while(true)
            {
                Socket connectionSocket=welcomeSocket.accept();
                BufferedReader inFromClient=new BufferedReader(new InputStreamReader(connectionSocket.getInputStream()) );
                DataOutputStream outToClient=new DataOutputStream(connectionSocket.getOutputStream());
                clientSentence=inFromClient.readLine();
                capitalizedSentence=clientSentence.toUpperCase() +" success "+ '\n';
                outToClient.writeBytes(capitalizedSentence);
            }
        }
    }