The Transmission Control Protocol (TCP) provides reliable, ordered delivery of a stream of octets from a program on one computer to another program on another computer. Here it is illustrated by sending text data from one system to another. BufferedReader class is used to process data at the client and server side.
//Client Side: ------------------------------------------------------------------------------------------------------ import java.io.*; import java.net.*; class TCPClient { public static void main(String argv[]) throws Exception { String sentence; String modifiedSentence; BufferedReader inFromUser = new BufferedReader( new InputStreamReader(System.in)); Socket clientSocket = new Socket("localhost", 6780); //6780 is the port used for TCP communication DataOutputStream outToServer = new DataOutputStream(clientSocket.getOutputStream()); BufferedReader inFromServer = new BufferedReader(new InputStreamReader(clientSocket.getInputStream())); System.out.print(" file name : "); sentence = inFromUser.readLine(); System.out.println("ffff --> "+sentence); outToServer.writeBytes(sentence+'\n'); modifiedSentence = inFromServer.readLine(); System.out.println("FROM SERVER: " + modifiedSentence); FileOutputStream f = new FileOutputStream("copy of "+sentence); DataOutputStream d = new DataOutputStream(f); byte fd[] = new byte[1024]; fd = modifiedSentence.getBytes(); d.write(fd); clientSocket.close(); } } //Server Side: ------------------------------------------------------------------------------------------------------- import java.io.*; import java.net.*; class TCPServer { public static void main(String argv[]) throws Exception { String clientSentence; String capitalizedSentence; ServerSocket welcomeSocket = new ServerSocket(6780); while(true) { Socket connectionSocket = welcomeSocket.accept(); BufferedReader inFromClient = new BufferedReader(new InputStreamReader(connectionSocket.getInputStream())); DataOutputStream outToClient = new DataOutputStream(connectionSocket.getOutputStream()); clientSentence = inFromClient.readLine(); System.out.println("Received: " + clientSentence); BufferedReader br = new BufferedReader(new FileReader(clientSentence)); String filecontent=""; //File content is cleared filecontent = br.readLine(); System.out.println("file : "+filecontent); outToClient.writeBytes(filecontent+'\n'); } } }