TCP Server

As a follow on from the IP Address in java, the next thing would be a server/client over the internet. This is a small demo on how to create TCP connections over IP Address (TCP basically means that the data sent over the connection will fully be sent, e.g. a linux cd image), shall do one in a UDP which is more of a send data and do not really care if data is sent across the network like radio, if you do miss part of a song it does not really matter.

So to start with, I am using the port number 9999, lets say that you are in a office with different phones running on different extension numbers but using the main telephone number to make calls on, so in this setup the IP address would be main office telephone number (one number to talk on) and the port number would be the different telephones extensions that you can talk on.

To create a server socket you need to pass in the port number as well.

ServerSocket theServerSocket = new ServerSocket(9999);

then to just wait for a connection to try and connect you

Socket sock = theServerSocket.accept();

which waits for a client connection (accept) , since the socket also has the clients IP address you can use that to make sure that you want to accept connections from that IP address if you wanted to, but to output the InetAddress you could use the “sock” from the above code

System.out.println("The client IP address is " + sock.getInetAddress());

the only other thing is that you can send data to the client which using a ObjectOutputStream with passing in the “sock” from the above code

ObjectOutputStream oos = new ObjectOutputStream(sock.getOutputStream());
oos.writeChars("Hi from the server");
oos.close();

Here is the full code

import java.io.IOException;
import java.io.ObjectOutputStream;
import java.net.InetAddress;
import java.net.ServerSocket;
import java.net.Socket;
 
public class TCPServer {
	// the IP class as such
	InetAddress theTCPServer;
	// port to talk over
	int portNumber = 9999;
	// the socket for the communication to happen on
	ServerSocket theServerSocket;
 
	/* 
	 * Setup the server socket communication 
	 */
	public TCPServer() {
		try {
			// create the server socket on the port number
			theServerSocket = new ServerSocket(portNumber);
			System.out.println("Server created on port : "+portNumber);
		} catch (IOException ExecIO)
		{
			System.out.println("Error creating the server socket : "+ExecIO.getMessage());
		}
	}
 
 
	public void connections()
	{
		try {
			// accept a connection 
			Socket sock = theServerSocket.accept();
			System.out.println("Server accepted connection, send to handler");
 
			// print out the clients IP Address
			System.out.println("The client IP address is " + sock.getInetAddress());
 
			// send the message to the client
			ObjectOutputStream oos = new ObjectOutputStream(sock.getOutputStream());
			System.out.println("Server socket opened");
			oos.writeChars("Hi from the server");
			oos.close();
 
			// close the socket
			sock.close();
 
		} catch  (IOException ExecIO)
		{
			System.out.println("Error creating connection : "+ExecIO.getMessage());
		}
	}
 
	public static void main(String[] args) {
		TCPServer theServer = new TCPServer();
		theServer.connections();
	}
}

save as TCPServer.java and then to compile, and run

javac TCPServer.java
java TCPServer

and the output would be something like

Server created on port : 9999
Server accepted connection, send to handler
The client address is /127.0.1.1
Server socket opened

you could use wireshark to watch what is happening.

Internet Address IP

With Java you can use the java.net package to find out details of your PC address or somewhere else (like www.google.com) with using the InetAddress class. The InetAddress is a implementation of the Internet Protocol basically.

To gain the local pc address you can use

InetAddress theHost = InetAddress.getLocalHost();
System.out.println("Local host address: "+theHost);

which would get the local PC address and display it to the screen, for me it would something like

Local host address: genux-laptop/127.0.1.1

you can get the individual parts of the above address, e.g. genux-laptop and 127.0.0.1

System.out.println("Local host name : " +theHost.getHostName());
System.out.println("Local address : "+theHost.getHostAddress());

and the output would be

Local host name :  genux-laptop
Local address : 127.0.1.1

you can also use the InetAddress to obtain remote addresses for example www.google.com so to pull details back from google you could use the getByName function that is within the InetAddress class as.

System.out.println("Host address of google.com : "+ InetAddress.getByName("www.google.com"));

Here is a full code that does the above in full

import java.io.*;
import java.net.*;
 
public class address {
		public static void main(String[] args)
		{
			// a inetaddress class holds details of internet protocol (IP) address
 
			InetAddress theHost = null;
			// you can get the local host (your PC) addresss
			try {
				theHost = InetAddress.getLocalHost();
				System.out.println("Local host address: "+theHost);
			}
			catch (UnknownHostException unknow)
			{
				System.out.println("Error : "+ unknow.toString());
				return;
			}
			// if there is no local host then, oppss!!.. you should really have a local host name
			// also you get can the local host name and address individual 
			String theHostName = theHost.getHostName();
			String theHostAddress = theHost.getHostAddress();
 
			System.out.println("The host name "+ theHostName);
			System.out.println("The host address " + theHostAddress);
 
			try {
				// you can a reverse look up as such by passing in the local name to get the IP address
				System.out.println("Host address by host name : "+ InetAddress.getByName(theHostName));
 
				// if you wanted to get a google host name then just pass in www.google.com
				System.out.println("Host address of google.com : "+ InetAddress.getByName("www.google.com"));
			}
			catch (UnknownHostException unknow)
			{
				System.out.println("Error : "+ unknow.toString());
			}
		}
}

and the output would be

Local host address: genux-laptop/127.0.1.1
The host name genux-laptop
The host address 127.0.1.1
Host address by host name : genux-laptop/127.0.1.1
Host address of google.com : www.google.com/216.239.59.105

Equals – why ? and why not ==

Object oriented programming allows for objects to be created on the fly with the keyword “new”. The new will create a new object on the heap memory space and then give that memory location to the variable name, for example.

class NewClass 
{
   private int x;
} ....
 
NewClass a = new NewClass();
NewClass b = new NewClass();

What is happening in memory is something like below, the a variable has a small space and so does b, because they are just “pointers” to the actual memory locations of the class that was created.

Variable Value
a 0x0102
b 0x0110

where as the memory on the heap space would actually hold the NewClass details for example.

Memory location Value
0x0102 NewClass – overhead details
0x0104 NewClass – x value
…. ….
0x0110 NewClass – overhead details
0x0112 NewClass – x value

So the actual value of a and b are just values within memory, this could give reason why the “==” (equals) does not work e.g.

if (a==b)

even if both of them have the same internal values of the NewClass x value, they are still actual pointing to different locations (which makes sense otherwise you are comparing the same object which would be silly). There is a few functions to do the comparsions of objects, Equals, Compare for example and if you implement these functions within your class you can then “compare” the two objects instead of the memory locations that are held within the variables (a 0x0102 and b 0x0110)

To implement a Equal function it would be something similar to

	public boolean Equals(Object obj)
	{
		if (x == ((ClassA)obj).xValue())
			return true;
                return false;
	}

where the obj (Object) passed is the same type as the Class e.g. NewClass and return true if they are same (after casting the object obj value to a ClassA structure).

Here is a bigger example with code for two java files, if you save this class as normal for java to have it the same as the class name e.g. ClassA.java

public class ClassA {
	private int x;
 
	public ClassA() { x =0;}
	public ClassA(int value) { x = value;}
 
	public int xValue() { return x; }
	public void setX (int value) { x = value;}
 
	public boolean Equals(Object obj)
	{
		if (x == ((ClassA)obj).xValue())
			return true;
		return false;
	}
 
	public int Compare(Object obj)
	{
		ClassA objA = (ClassA)obj;
		if (x > objA.xValue())
			return 1;
		else if (x < objA.xValue())
			return -1;
		else
			return 0;
	}
}

this file also includes the Compare function method, so the returns have to be normal to java comparison e.g. 1 means > (greater than) , 0 = same, -1 < (less than), it is up to you to implement to make sure that this kinder of comparison adhears to how you want the class is greater than another class, could be a X value as above, or could that you call the first class number 1 and the second of that type of class 2.. it is up to you. and then save this as Test.java

public class Test {
 
	/**
	 * @param args
	 */
	public static void main(String[] args) {
		ClassA a = new ClassA();
		a.setX(10);
		ClassA a2 = new ClassA();
		a2.setX(10);
		if (a==a2)
			System.out.println("Yep the same");
		else
			System.out.println("nope not the same");
 
		if (a.Equals(a2))
			System.out.println("Yep the same");
		else
			System.out.println("nope not the same");
		a2.setX(11);
		int comparsion = a.Compare(a2);
		if (comparsion == 0)
			System.out.println("Same");
		else if (comparsion == 1)
			System.out.println("greater");
		else	// only -1 left.
			System.out.println("less than");
 
	}
 
}

compile them you just need to javac Test.java and that will compile the ClassA.java file as well, then to run

java Test
 
nope not the same
Yep the same
less than

Java applet – hello world

A java applet is a web object that allows you to do some funky things within a web page, you could even have a game on the screen with a java applet. But as normal you have to start from the start as such, the most used starts are the classic “hello world” example.

In a java applet, it is basically a class called Applet that you extend from and this has all of base code inside it so you only need to implement the virtual functions

  1. init
  2. start
  3. paint
  4. destory
  5. stop

And these are the basic functions that allow you to call other classes of your choice. The init – (initialize), setups up the environment of your choice, start is where the application (GUI interface) will run within, paint is what is painted to the applet screen, destory is when you destory the applet you may need to clean up some code, stop is when the application/applet is stopped.

The main basic class will extend from a applet (java.applet.Applet) so you will need to import that class library

import java.applet.Applet;
 
// basic class extends the applet
public class HelloWorld extends java.applet.Applet {

and then implement the functions start,init,stop,destory and paint if required. Below is more code that will resize the basic applet object and display (paint) the words Hello World using the Graphics class object drawString method.

import java.awt.Graphics;		// need this for the Graphics part of the paint function
import java.applet.Applet;		// to extend from.
 
public class HelloWorld extends java.applet.Applet {
 
    // resize the screen 
    public void init()
    {
	resize(150,25);
    }
 
    public void start()
    {
    }
 
    // draw with the Graphics class object a string on the canvas, point 50, 25
    public void paint(Graphics graphicsObj)
    {
	graphicsObj.drawString("Hello World!", 50,25);
    }
 
    public void stop()
    {
    }
 
    public void destroy()
    {
    }
}

Is you save that as “HelloWorld.java” and then you need to compile it into a class file (which is a common object file that java can read to run within the virtual machine).

javac HelloWord.java

which will output the HelloWorld.class file, which you will need to include into the html code applet tag, below is the HTML code

<HTML>
<head>
<title>A hello world</title>
</head>
<body>
Test output of the program
<applet code="HelloWorld.class" width=150 height=25>
</applet>
</body>
</HTML>

The output would be

Test output of the program

Note: If you look at the source code of this page, it will say

<applet code="HelloWorld.class" codebase="/Appletsexamples/"  archive="HelloWorld.jar" width="150" height="25"></applet>

I had to add in the codebase and archive because of the hosting, to create a jar file you just need to do

jar cf <tarname> <file(s) name>
 
jar cf HelloWorld.jar HelloWorld.class

The jar file is basically a zipped archive.

Arrays

Arrays are ways of having a block of memory allocated to a single variable type, this allows for holding the national lottery numbers within an array of 6 instead of actually having 6 different variables, saves on variable overload

e.g.

int value1 = 1;
int value2 = 2;
int value3 = 3;
int value4 = 4;
int value5 = 5;
int value6 = 6;

and instead you could just have

int[] values = {1,2,3,4,5,6};

This is example code of how to use arrays.

public class arraytest
{
       public static void main(String[] args)
       {
              // the main method passes in parameters from the console command line 
              // e.g. ./arraytest hi there, hi there are two parameters
              for (int i =0; i < args.length; i++)
              {
                     System.out.println(args[i]);
              }
 
              // to create a array of numbers
              int[] intarray = {0,2,3,4};
 
              for (int i =0 ; i < intarray.length; i++)
              {
                     System.out.println(intarray[i]);
              }
       }
}

After compiled the above code and executed the class file that would be generated by

Java arraytest hi there

The output of the program would be

hi
there
0
2
3
4

But if the console command line was empty then just the number values would be outputted since they are inserted into the code and the ‘hi there’ was inserted manually on the command line.

Interfaces

An interface describes what functions an implemented class will have to code. E.g. if a class was a car and the interface had functions for how many doors etc, then a class of Vauxhall that implements the interface would have to code the function to return the correct amount of doors.

Here is the code, I usually find the code explains it better.

// defines the fuctions that have to be implemented by a implementable class
interface implementThese
{
       void printHi();       // have to implement these
       void printBye();
}
 
// the interClass will implement the interface implementThese
class interClass implements implementThese
{
       public void printHi()
       {
              System.out.println("Hi");
       }
 
       public void printBye()
       {
              System.out.println("Bye");
       }
}
 
class inter
{
       public static void main(String args[])
       {
              interClass in = new interClass();
              // call the classes functions.
              in.printHi();
              in.printBye();
       }
}

If you save as inter.java, and then run the output will be

Hi
Bye

There can be many interfaces per class to be implemented.

Generics

A Generic is a way to declassify the type of variable used, e.g. if there was a function to add up two integer values, but you had two double values, then the int function would not function correctly, so there would be a need to function overload the function to allow for the double increment as well. But just envisage that the same function would be required for characters, floats, personally created ones etc, then there would be more functions per type of variable than the actual work done.

A generic class negates this by allowing any class type passed to the function, as long as the type has the standard increment process defined, it will work with any type.

This will demonstrate the basics of the generics.

// the class for the generics (the T is the object of any type)
class genericsClass<T> 
{
       T val;              // private object val of type T
       public genericsClass(T t)       // constructor for the class
       {
              val = t;              // set the internal to the passed value
       }
 
       public T returnValue()       // return the internal value
       {
              return val;
       }
}
 
// main runable class
public class generics
{
       public static void main(String args[])
       {
              // create a Integer class with a default value of 3
              genericsClass<Integer> genInt = new genericsClass<Integer>(3);
              System.out.println("Value= " + genInt.returnValue());
 
              // create a String class with a default value of "hi there"
              genericsClass<String> genStr = new genericsClass<String>("hi there");
              System.out.println("Value = " + genStr.returnValue());
       }
}

If you save the code and run with java version 1.5 + (since this was part of java 1.5). The output will be

Value = 3
Value = hi there

As you can see the same class is able to use both integer and strings as the default variable type.