Tuesday, 27 January 2015

Implement chatting using TCP


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

class TCPServer{
      public static void main(String[] args) throws IOException{
            String clientsentence;
            String capitalizedSentence;

            ServerSocket welcomeSocket = new ServerSocket(6789);

            while(true){
                  Socket connectionSocket = welcomeSocket.accept();

                  DataInputStream inFromClient = new DataInputStream(connectionSocket.getInputStream());

                  DataOutputStream outToClient = new DataOutputStream(connectionSocket.getOutputStream());

                  clientsentence = inFromClient.readLine();

                        System.out.println("From Client: " + clientsentence);

                  capitalizedSentence = clientsentence.toUpperCase()+'\n';

                  outToClient.writeBytes(capitalizedSentence);
            }
      }
}



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

class TCPClient{
      public static void main(String[] args) throws IOException {
            String sentence;
            String modifiedSentence;

            Socket clientSocket = new Socket("localhost",6789);

            DataInputStream inFromUser = new DataInputStream(System.in);

            DataOutputStream outToServer = new DataOutputStream(clientSocket.getOutputStream());

            DataInputStream inFromServer = new DataInputStream(clientSocket.getInputStream());


            sentence=inFromUser.readLine();
            outToServer.writeBytes(sentence+'\n');

            modifiedSentence=inFromServer.readLine();
            System.out.println("From Server : "+modifiedSentence);

            clientSocket.close();                    
      }

}


OUTPUT :

run:
From Client: Hiii From Server

No comments:

Post a Comment