Alright, this tutorial is going to be an introduction to sockets in Java. Before reading this, i'd reccommend some experience with basic Java programming.
Alright, let's start a new Java class:
public class yourClass {
public static void main(String[] args) {
Now, the first thing we're going to do is check if the program was given the correct amount of arguments when ran, add this to your code:
if (args.length != 1) {
System.out.println("Usage: Client <address>");
return;
}
Okay, now after the user has ran this program (and entered the host address with it), we want to convert the host to an IP so that Java can connect to it. Add this to your code:
InetAddress addr = null;
try {
addr = InetAddress.getByName(args[0]);
} catch (UnknownHostException e) {
System.err.println("Error, invalid host");
return;
}
Alright, what we just did is take the host (ex. helnet.org) that the user enters into the program and use the getByName function to convert it to an IP so it is possible to connect to later.
Now, our next step is to make the socket, so we can connect to the host. Add this to your code:
Socket sock = null;
try {
sock = new Socket(addr, 21);
} catch (IOException e) {
System.err.println("Error creating socket");
return;
}
Alright. We've just created a socket. That will connect us to the host specified by the user on port 21 (feel free to change the port to whatever you'd like). Now. The next thing we need to do is create an Input Stream so we can read the input of the server. Add this:
InputStream input = null;
try {
input = sock.getInputStream();
} catch (IOException e) {
System.out.println("Error creating input stream");
}
Alright, that's done. Now for the final bit of code. What this part will do is create a buffer reader to read the reply the server gives us when we connect to it. Add this:
BufferedReader readMe = new BufferedReader(new InputStreamReader(input));
String readThis = null;
try {
while((readThis = readMe.readLine()) != null)
System.out.println(readThis);
} catch (IOException e) {
System.err.println("Error reading line");
return;
}
Alright, end the class and main with two more curly braces and the program is done! When you run the program you should get the server's FTP message, for example, when done with helnet.org:
220---------- Welcome to Pure-FTPd [TLS] ----------
220-You are user number 10 of 50 allowed.
220-Local time is now 15:45. Server port: 21.
220-IPv6 connections are also welcome on this server.
220 You will be disconnected after 15 minutes of inactivity.