Tutorial 01 : Network basis

Tutorial Advanced Download Section

This tutorial is an introduction to network. I will show you how to write a basic TCP Client/Server application (TCP : Transmission Control Protocol).
This is a simple application that is used here to send/receive datas between a client and the server.
 

The basic notions was seen in Lesson 1. Please read it before this tutorial.

A client/server aplications is always composed of two separates applications :
  Client Side
  Server Side

We will see the client side first, it is the simplest. Server side is similar but a little more complex due that many client can connects themself to the sever.
 

The client application is composed of these classes :
    -> client               (main class)
    -> ClientConnection, Connectable, Protocol
 

We've seen in Lesson 1 that the client creates a Socket to connects himself to the server.
To creates a Socket in Java (package java.net), it is very simple. You just need to know the IP or the name of the server and the communication port that the server listening.

This socket allows you to get the input and output streams. To send or read datas, just read or write in these streams.
 

Connect to the server

    //Creates the socket
    Socket socket = new Socket(ip, port);

 

IP address is represented in Java by the class InetAddress (also in java.net).

You can creates an InetAddress object using the host name or its IP. I will suppose that you run the server in your machine (localhost), but it is the same if you run in a different computer (just replace the IP or the name).
Here are different ways to creates an InetAddress for the localhost (127.0.0.1) :

IP of the localhost

    //IP address of the localhost
    InetAddress localhostIP = InetAddress.getLocalHost();
    InetAddress localhostIP = InetAddress.getByName("localhost");
    InetAddress localhostIP = InetAddress.getByAddress("127.0.0.1", new byte[]{127, 0, 0, 1});
    InetAddress localhostIP = InetAddress.getByAddress("localhost", new byte[]{127, 0, 0, 1});

 

To send or receive data, use the InputStream/OutputStream of your Socket object.

InputStream/OutputStream

    //Output stream for sending datas
    socket.getOutputStream()
    //Input stream for receiving datas
    socket.getInputStream()


For sending datas, write in the OutputStream. To read datas received, read in the InputStream.

Send & receive datas

    /*
     * SEND DATAS
     */
    //Sending a String

    String s = ...;
    OutputStreamWriter out = new OutputStreamWriter(getSocket().getOutputStream());
    out.write(s);
    out.flush();
    //Sending a byte[]
    byte[] bytes = ...;
    OutputStream out = getSocket().getOutputStream();
    out.write(bytes);
    out.flush();
    //Sending an InputStream
    InputStream is = new FileInputStream(new File(...));
    OutputStream out = getSocket().getOutputStream();
    int c = -1;
    while ((c = is.read()) != -1)
        out.write(c);
    out.flush();
   
    /*
     * RECEIVE DATAS
     *
     * Note: you can read data only if you have received (checked with in.available())
     */
    //Reading into a byte[]

    InputStream in = getSocket().getInputStream();
    if(in.available() > 0)
    {
        byte[] input = new byte[in.available()];
        in.read(input);
    }

Note :
If you having some troubles with Buffered input/output (like bad/inccomplete transfert of datas ...), try using non buffered stream.
 

We've seen how to send data to the server and receive datas from it. So, the client can exchange informations.
But, it is not sufficient to communicates. Effectively, the client don't know how to decode the data received. This part will not be seen in this tutorial but in Tutorial 2.

When the client have finished to "talk" with the server, he can disconnect him by closing its socket.

Disconnection of the client

    //Close the socket
    socket.close();

 

The server application is composed of these classes :
    -> server             (main class)
    -> ServerConnection, ServerLink, ServerLinkCreator
 

The server side is similar to the client side. But, there is also some differencies.

A server don't use a socket but a ServerSocket.
This kind of socket are used to listen connection request of clients, on a specific communication port. For example, http server listen on the port 80.
 

Opening the server port

    //Open a communication port
    int port = ...;
    ServerSocket serverSocket = new ServerSocket(port);

 

Now the ServerSocket is bounded on the port, you can start listening for client connection.

Listening on the port

    //Listening on the communication port
    Socket socket = serverSocket.accept()

Note :
This methods blocks untils a connection is made (that is to say untils a client try to connect to the server). If you don't want to block you application, call this method in a thread.

Once a client is accepted, a Socket is created.
This is the endpoint of the client/server connection, on the server side. On the client side, when the connection is accepted, a socket is also created forthe client (see above).

The use of this socket is identical the client socket. So, to send and receive data to the client, use the same way than for the client.


The particularity of the server is that multiple connection are allowed at the same time. This means that you can communicate with multiple client at the same time.
The effect of this is that the server should store a list of socket, each one corresponding to connection with a client.
 

The disconnection of the server is done with serverSocket.close().
Remember to close the connection of all clients.
 

I've mentionned that clients can't understand the server without knowing how to decode server messages. This will be added in the following tutorial.
 

I've tried a strange thing : connects an internet browser to my server application.
I've achieved to make a connection and send informations to Microsoft Internet Explorer and Mozilla Firefox (I don't try with another browser but I think it should works).

In this tutorial, we have connected our client application to the server ones. But, you can connects a different client application (not written in Java ! ) to your server application. In this case, the client is an internet browser.
 

Run the server application, open the communication port and accept a client.
If the server is runned on the localhost and listen to the communication port 8765, write this URL in the address bar of your browser :
    http://localhost:8765/
or
    http://127.0.0.1:8765/
(Replace localhost or 127.0.0.1 by the server IP and 8765 by the communication port that the server listen).

By putting this URL in the address bar of your browser, it makes a GET request (HTTP request). So, he waits that the server sends him the corresponding ressource.
The server receive this request and he can send "all" he want to your browser (there are nevertheless some restriction on the type of data send).

After the server have finished to send datas, he needs to close his output stream (stream used to send datas). To do this, close the connection. Then, the browser should normally prints datas sent.

Here, I've sended "Welcome from Network Tutorial 01" to my Firefox browser :


Connection to Firefox

This thing will be used (and explain in details) in Tutorial 3.
 

I've show you how to communicates with two computers using a client/server application.

Ordinarily, there are more than two computers. There are a server and a lots of clients. The server is, generally, always connected and the client connects himself when he wants to use the service provided by the server.
Clients communicates between them by the intermediate of the server. All messages are send to the server, then the server redistribute messages to their respective addressees. So, the server is like a postman.

Some uses of a Client/Server application was shown in Lesson 1.
 

To run the server and the client application, use something like this :
    java -classpath ./ clientMain "127.0.0.1" 8765
    java -classpath ./ serverMain 8765
Replace 127.0.0.1 by the server IP or the server name. You must specified the same communication port (here I use 8765).

The server must open its communication port (choice 1 in the menu) before clients tries to connects to him.

Rem :
You can connects more than one client on the server and communicates with only the client selected.
 

Back

Next turorial

Last modified on 01/07/2010
Copyright © 2004-2010 Jérôme JOUVIE - All rights reserved. http://jerome.jouvie.free.fr/