oval
Centre International de Mathİmatiques Pures et Appliquİes
International Center for Pure and Applied Mathematics


A CIMPA-UNSA-INRIA-UNESCO-VIETNAM SCHOOL ON


Objects and Network
Sockets and Client/server Courses


Emmanuel Chailloux
Emmanuel.Chailloux@lip6.fr
http://www-spi.lip6.fr/~emmanuel

SUMMARY

Distributed memory

Each processus has its own memory space and communicates with the others through a medium (protocols).


Ş explicit communication and implicit synchronization!!!

sockets.tex[Prises de communication en Java]

Communication on sockets : socket types

Sockets communication have : Communications are asymmetric!!!

Communication on sockets

Server scheme :


Communication on sockets

Client scheme :


Main classes for networking
in package java.net :
Low level: High level:
ServerSocket and Socket classes
Main methods:
ServerSocket:Socket:
ServerSocket(int port)Socket(String host,int port)
Socket accept() 
void close() 
 InputStream getInputStream()
 OutputStream getOutputStream()
All these methods can throw an IOException,
and need throws IOException.

cl-se.tex[Client/Server in Java]
Example : CAPITALIZER server

Service: the server receives a line, converts it in CAPITALIZE and sends it to its client.

Organization:
Server side : two classes : Client side : one trivial class : Protocol:

A line which contains only the word end closes the connection with the client!!!

Server part
indentation
import java.io.*;
import java.net.*;

public class Server extends Thread {
protected static final int PORT =45678;
protected ServerSocket hear;


Server ()
{
try
{hear =
new ServerSocket(PORT);}
catch (IOException e)
{System.err.println(e.getMessage());
System.exit(1);
}
System.out.println(
"Server hears on port : "+PORT);
this.start();
}

public void run ()
{
try
{
while (true)
{Socket client=hear.accept();
Connection c =
new Connection (client);}}
catch (IOException e)
{System.err.println(e.getMessage());
System.exit(1);}
}

public static void main (String[] args)
{
new Server();}

}

Connection part
indentation
import java.io.*;
import java.net.*;

class Connection extends Thread {
protected Socket client;
protected BufferedReader in;
protected PrintWriter out;

public Connection(Socket client_soc)
{client=client_soc;
try
{in=
new BufferedReader(
new InputStreamReader(client.getInputStream()));
out=
new PrintWriter(client.getOutputStream());}
catch (IOException e)
{
try {client.close();}
catch (IOException e1){}
System.err.println(e.getMessage());
return;}
this.start();
}
public void run()
{
try
{
while (true)
{String line=in.readLine();
if (line.toUpperCase().compareTo("END")==0) break;
System.out.println(line.toUpperCase());
out.println(line.toUpperCase());
out.flush();
}}
catch (IOException e)
{System.out.println(
"Connection : "+e.toString());}
finally
{
try {client.close();}catch (IOException e) {}}

}

}

Client part
indentation
import java.io.*;
import java.net.*;
public class Client {
protected static final int PORT=45678;
public static void main(String[] args)
{
Socket s=
null;
if (args.length ¹ 1)
{System.err.println(
"Usage: java Client <hote>");
System.exit(1);}
try
{s=
new Socket (args[0],PORT);
BufferedReader inChannel =
new BufferedReader(
new InputStreamReader(s.getInputStream()));
DataInputStream console =
new DataInputStream (s.getInputStream());
PrintWriter outChannel =
new PrintWriter(s.getOutputStream());
System.out.println(
"Connection : "+ s.getInetAddress()+" port : "+s.getPort());
String line =
new String();
char c;
while (true)
{System.out.print(
"?"); System.out.flush();
line =
"";
while ((c=(char)System.in.read()) ¹ '\n') {line=line+c;}
outChannel.println(line);
outChannel.flush();
line=inChannel.readLine();
if (line == null)
{System.out.println(
"Connection disapears"); break;}
System.out.println(
"!"+line);
}
}
catch (IOException e) {System.err.println(e);}
finally {try {if (s ¹ null) s.close();}catch (IOException e2) {}}
}
}

Execution

Server side:
$ java Server
Server hears on  port : 45678
THIS IS THE END
MY ONLY FRIEND THE END
Client side:
$ java Client asimov
Connection : asimov/132.227.69.15 port : 45678
?this is the end
!THIS IS THE END
?my only friend the end
!MY ONLY FRIEND THE END
?end
Connection disappears
Internet services

nameportsocket typedescription
ftp21tcpfile transfer
telnet23tcpconnection to remote systems
smtp25tcpmail protocol
name42udpnameserver
tftp69udptrivial ftp
http80tcpfor the Web
pop2109tcpPost office

A same service can exist on different ports as http. The Internet protocols are described in documents Request For Comments (RFCs),available online at : http://www.internic.net/std

Others services

From Unix world:

Others examples:
World Wide Web

HTTP small description

HTTP protocol (http://www.w3.org/pub/WWW/Protocols/) :


HTTP messages consist of requests from client to server and responses from server to client.
HTTP-message   = Request | Response    

       Request        = Request-Line
                          ...   CRLF

       Request-Line = Method SP Request-URI
                       SP HTTP-Version CRLF

       Request-URI  = absoluteURI | abs_path

       Method         = "GET"                   
                      | "HEAD"                  
                      | "POST"                  
Example :
GET /pub/WWW/TheProject.html HTTP/1.0

Example : an http client

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

public class http {
public static void main(String []args){
String webserver =
"ufr-info-p6.jussieu.fr";
int http_port = 80;
Socket sock;
DataInputStream dis;
PrintStream ps;

switch (args.length) {
case 0: break;
case 1: {webserver=args[0]; break;}
case 2: {http_port = (int)Integer.parseInt(args[1]);break;}
default : {System.err.println("Usage: java http <hote> <port>");
System.exit(1);}
}

try {
sock =
new Socket(webserver, http_port);
dis =
new DataInputStream(sock.getInputStream());
ps =
new PrintStream(sock.getOutputStream());

ps.println(
"GET /index.html");
String s=
null;
while ( (s=dis.readLine()) ¹ null) {
System.out.println(s );
}
sock.close();
}
catch (Exception e) {System.err.println("IO:"+e.getMessage());
System.exit(2);}


}
}

Running http client

$ java http www.ufr-info-p6.jussieu.fr
<!-- index.html -->
<HTML>
<HEAD>
<TITLE>Serveur de l'UFR d'Informatique
de Pierre et Marie Curie</TITLE>
</HEAD>
<BODY>
....
<A HREF="mailto:webdev@ufr-info-p6.jussieu.fr">webdev</A>
dernière modification le 30/04/98 à 14h43
</BODY>
</HTML>
<!-- index.html -->


using URL class
in java.net package

http client : new version
indentation
import java.net.*;
import java.io.*;

public class wurl {

public static void main (String a[]) {
BufferedReader dis;
try {
URL u =
new URL("http://cadillac.lip6.fr/index.html");
dis =
new BufferedReader(
new InputStreamReader(u.openConnection().getInputStream() ));
String s;
while ( (s=dis.readLine()) ¹ null) {
System.out.println( s );
}
}
catch (Exception e) {System.out.println( e ); }
}

}

Http servers and dynamic pages

Dynamic pages don't exist before in the server, but are generated by programs!!!

CGI : Common Gateway Interface


Input/Output to CGI

Remarks

Applet

Database servers

API JDBC: Java DataBase Connectivity To use JDBC:
JDBC interfaces
in java.sql package
DriverManager: Connection: Statement: ResultSet:
basic example : SELECT
indentation
Connection con = DriverManager.getConnection (
"jdbc:mysql:"+machine+":"+port+"/"+dbname, "login", "password");
Statement stmt = con.createStatement();
ResultSet rs = stmt.executeQuery(
"SELECT name, age FROM Table1");
while (rs.next()) {
int x = rs.getInt("age");
String s = rs.getString(
"name");
System.out.prinln(
"name: "+ name+" age: "+age);
}

basic example : UPDATE
indentation
java.sql.PreparedStatement ps =
conn.createStatement(ªUPDATE T1 SET cat=? WHERE age=?º);

ps.setString(1, ªYoungº);
for (int i = 14; i < 19; i++) {
ps.setInt (2, i);
int nbTuples = ps.executeUpdate();
System.out.println (
"age: " + i + " nb: " + nbTuples);
}

Interest
Advantages: Disadvantages:
Bridge with ODBC

ODBC : (Open Database Connectivity) :
standard interface between application program and database
using for MS Access on Windows, Informix on Linux, ...


Bridge ODBC:JDBC : URL format :
jdbc:odbc:machine:port/myDB


needs JDBC-ODBC bridge + driver ODBC (given with DBMS)

SQLJ : Embedded SQL
Simplified code
indentation
//SQLJ
float w; java.sql.Date x; int y; String z;
...
#sql {SELECT C1, C2 INTO :w, :x FROM TAB WHERE C3 = :y AND C4 = :z };


//JDBC
float w; java.sql.Date x; int y; String z;
...
PreparedStatement s = connection.prepareStatement(
"SELECT C1, C2 FROM TAB WHERE C3 = ? AND C4 = ?");
s.setInt(1, y);
s.setString(2, z);
ResultSet r = s.executeQuery();
r.next();
w = r.getFloat(1);
x = r.getDate(2);
r.close();
s.close();

Architecture for clients/servers

two tiers:


Architecture for clients/servers

three or more tiers:



This document was translated from LATEX by HEVEA.