Free Data Structures and Algorithms Course









Subscribe below and get all best seller courses for free !!!










OR



Subscribe to all free courses

How to connect to a remote server through a Java program ?

Program to demonstrate a way to connect to a remote server by a simple Java program

package com.hubberspot.networking.example;

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

public class RemoteConnection {
  public static void main(String[] args) {
    String host = "tock.usno.navy.mil";
  
    try {
      Socket socket = new Socket(host, 13);
      InputStream timeStream = socket.getInputStream( );
      StringBuffer time = new StringBuffer( );
      int c;
      while ((c = timeStream.read( )) != -1) 
        time.append((char) c);
      String timeString = time.toString().trim( );
      System.out.println("It is " + timeString + " at "
        + host);
    } 
    catch (UnknownHostException e) {
      System.err.println(e);
    }
    catch (IOException e) {
      System.err.println(e);
    }
  } 
} 

Output of the program :

It is Thu May 3 17:08:47 2012 at tock.usno.navy.mil

 
© 2021 Learn Java by Examples Template by Hubberspot