Pin It

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

Please Give Us Your 1 Minute In Sharing This Post!
SOCIALIZE IT →
FOLLOW US →
SHARE IT →
Related Posts Plugin for WordPress, Blogger...

Post your related queries below ...

comments powered by Disqus
Powered by Blogger.
 
© 2012 Learn Java by Examples Template by Hubber Spot