Sunday 20 January 2013

TCP Client-JAVA


// usage : java tcpClient <server> <port>
import java.net.*;
import java.io.*;

public class tcpClient {



    public static void main(String[] args) {

 Socket socket = null;
 String lineToBeSent;
 String server="localhost";
 BufferedReader input;
 PrintWriter output;
 int port=1500;
// read arguments
    try {
      server = args[0];
      port = Integer.parseInt(args[1]);
 }
 catch (Exception e) {
  System.out.println("Wrong input");
 }


 // connect to server
 try {
     socket = new Socket(server, port);
     System.out.println("Connected with server " +
       socket.getInetAddress() +
       ":" + socket.getPort());
 }
 catch (UnknownHostException e) {
     System.out.println(e);
     System.exit(1);
 }
 catch (IOException e) {
     System.out.println(e);
     System.exit(1);
 }

 try {
     input = new BufferedReader(new InputStreamReader(System.in));//for reading the entry from the keyboard
     output = new PrintWriter(socket.getOutputStream(),true); //for sending input data to the Server through the socket

     // get user input and transmit it to server
     while(true) {
  lineToBeSent = input.readLine();
  // stop if input line is "."
  if(lineToBeSent.equals(".")){break;

  }
  output.println(lineToBeSent);
     }

 }
 catch (IOException e) {
  System.out.println(e);
 }
 try {
    socket.close();
 }
 catch (IOException e) {
     System.out.println(e);
 }

    }
}