Sunteți pe pagina 1din 49

EE2E1.

JAVA Programming

Lecture 9

Network Programming
Contents
 Introduction to networks
 TCP/IP Sockets
 A simple client program
 A simple server program
 A server with multiple clients
 Example – a simple email program
 URL connections
 Advanced networking technologies in Java
Introduction to Networks
 Network programming is surprisingly easy in Java
 Most of the classes relevant to network
programming are in the java.net package
 Sending data out onto a network involves attaching
a stream to a network connection (socket) and using
the stream I/O functions we looked at in a previous
lecture
 The main issues to consider are client/server
architectures and attaching multiple clients to a
server
 First we will look an introduction to networking
and the TCP/IP protocol
Internet Protocol (IP)
 Data is transmitted between computers in packets
 Each packet is marked with a destination
address
Server
Client
14
30

80
Internet Server Ports

130.65.83.25 30 data

Network packet
 Each 4 byte address is the IP address
 Normally we refer to computers with domain
names
 www.bham.ac.uk
 java.sun.com
 The translation from domain name to IP
address is carried out using DNS (Domain
Name Service)
 IP has no provision for re-transmission in case
of failure to deliver packets
 This is the job of the Transmission Control
Protocol (TCP)
 Most internet programs (eg the WWW, email
etc) are based on TCP/IP
TCP/IP Sockets
 A TCP/IP socket enables a java program
running on a client machine to open a
connection with a web server
 There is a socket on both the client and
server sides
 Client server communication is carried
out through input and output streams
Client output Server input
stream stream

Client Server
socket socket

Client input Server output


stream stream
A simple client program
 Java has a Socket object which is an abstraction
for a TCP/IP network endpoint to a client
computer
int HTTP_PORT=80;
Socket s= new Socket(“java.sun.com”,HTTP_PORT);
InputStream instream=s.getInputStream();
OutputStream outstream=s.getOutputStream();

 Connects to a server specified by the hostname


“java.sun.com” and creates I/O streams
 We can also directly specify the IP address
instead of a string
 Java has a InetAddress class to specify IP
addresses
 The (static) method getByName()
converts from a hostname to an
InetAddress

int HTTP_PORT=80;
InetAddress address=InetAddress(“java.sun.com”);
Socket s= new Socket(address,HTTP_PORT);
 Note that Java also provides a mechanism
for the user datagram protocol (UDP) which
is a simpler transport protocol that TCP
 The Datagram socket is the abstraction to
a UDP socket
 The difference between TCP and UDP is
like the difference between a telephone
conversation (albeit sent in packets) and
sending a letter
 As it stands, attempting to read from a
socket will block until data becomes
available
 Its possible to set a timeout (in ms) after
which a socket read will throw an
exception
int HTTP_PORT=80;
Socket s= new Socket(“java.sun.com”,HTTP_PORT);
s.setSoTimeOut(5000); // 5 seconds
InputStream instream=s.getInputStream();

try{ // read socket}


catch(InterruptedIOException e) { // process exception}
 The above code assumes we have already
created a Socket object from which to call
setSoTimeOut()
 But the Socket constructor can itself
block if it can’t make a connection
 This is possible if the server is
unavailable
 Needs a multi-threaded solution
class SocketOpener implements Runnable
{
public void SocketOpener(String aHost, int aPort,
int aTimeOut) {}

public Socket openSocket()


{
Thread t=new Thread(this);
t.start(); // Calls the run method
try
{
t.join(timeOut); // Returns when thread dies or timeout expires
}
catch (interruptedException e) {}
return socket;
}

public void run()


{ // Opens a socket
try{socket=new Socket(host,port);}

catch (IOException e) {}
}

private int timeOut;


private String host;
private int port;
private Socket socket;
};
 We can now implement a simple client program
which opens a socket to communicate with a web
server
 The hostname is supplied from the command
line
 A GET command is sent to the web server

 This is a HTTP command to return the


requested item
 For example “GET / HTTP/1.0” means get
the root page (/) from the host
 The server will then return the requested
information which is just HTML text
public class WebGet
{
public static void main(String[] args)
{
// Read command line args
String host;
String resource;

if (args.length==2)
{
host=args[0];
resource=args[1];
System.out.println("Getting " + resource + " from " + host);
}
else
{
System.out.println("Getting / from java.sun.com");
host="java.sun.com";
resource="/";
}
try
{
// Open socket
final int HTTP_PORT=80;
SocketOpener so=new SocketOpener(host, HTTP_PORT, 10000);
Socket s=so.openSocket();

// Get streams
if (s!=null)
{
InputStream instream=s.getInputStream();
OutputStream outstream=s.getOutputStream();

// Turn streams in scanners and writers


Scanner in=new Scanner(instream);
PrintWriter out=new PrintWriter(outstream);

// Send command
String command="GET " + resource + " HTTP/1.0\n\n";
out.print(command);
out.flush();
// Read response from the server
while (in.hasNextLine())
{
String input=in.nextLine();
System.out.println(input);
}

// Close socket
s.close();
}
else
System.out.println("Error - couldn't open socket");
}
catch(IOException e) {}
}
}
A simple server program
 A server is a program which waits for a
client to connect to it at a specified port
 Normally a server would specify some
application level protocol (such as HTTP)
enabling clients to interact with the server
 To start with, we will look at a simple server
which simply echo’s the text sent to it by the
client
 We will use telnet as the client to test out
our server
 A ServerSocket object is created to establish a
server connection
 The accept() method then waits for a client to
connect
 accept() waits indefinitely and returns a Socket
object that represents the connection to the
client

int portNumber=8250;
ServerSocket s=new ServerSocket(portNumber);
Socket clientSoc=s.accept();
public class EchoServer
{
public static void main(String[] args)
{
try
{
ServerSocket s=new ServerSocket(8250);
Socket clientSoc=s.accept();
BufferedReader in=new BufferedReader(new
InputStreamReader(clientSoc.getInputStream()));

PrintWriter out=new
PrintWriter(clientSoc.getOutputStream(),true);

out.println("Hello client! Enter BYE to exit");


boolean done=false;
while (!done)
{
String line=in.readLine();
if (line==null) done=true;
else
{
out.println("Echo: " + line);
if (line.trim().equals("BYE"))
done=true;
}
}
clientSoc.close();
}
catch(Exception e){}
}
}
 We can run the telnet client on the local
host (IP 127.0.0.1) at port 8250
 Use telnet command

open 127.0.0.1 8250


A server with multiple clients
 In the real world a server will want to link to many
clients
 Examples include servers providing
information (such as weather or travel info) or
online ticket booking
 Clearly we don’t want a single client program
to ‘hog’ a server and prevent other clients from
accessing it
 By implementing a multi-threaded server, we
can allow multiple connections
 We simply need to create a new thread to
handle each newly accepted client
connection
int portNumber=8250;
ServerSocket s=new ServerSocket(portNumber);

while(true) // accept multiple clients


{
Socket clientSoc=s.accept();
Thread t=new ThreadedEchoHandler(clientSoc);
t.start(); // Handle the client communication
}
 We can implement 2 classes,
MultiThreadedEchoServer and
ThreadedEchoHandler to handle multiple
client connections
 MultiThreadedEchoServer creates
ThreadedEchoHandler objects for each
client
 ThreadedEchoHandler extends Thread
and its run() method handles client I/O
 Its implementation is the same as the
main method of the EchoServer class
MultiThreadedEchoServer
object

ThreadedEchoHandler
ThreadedEchoHandler
object ThreadedEchoHandler
object
object

Telnet Telnet Telnet


public class MultiThreadedEchoServer
{
public static void main(String[] args)
{
int clientID=1;
try
{
ServerSocket s=new ServerSocket(8250);
for (;;)
{
Socket clientSoc=s.accept();
System.out.println("New client connection” + clientID);
new ThreadedEchoHandler(clientSoc,clientID).start();
clientID++;
}
}
catch(Exception e){}
}
}
An email program
 As a simple example of socket
programming we can implement a program
that sends email to a remote site
 This is taken from Core Java, vol 2,
chapter 3
 Email servers use port number 25 which is
the SMTP port
 Simple mail transport protocol
 A client socket to the mail server can be
opened on port 25
Socket s=new Socket(“engmail.bham.ac.uk”,25);

 SMPT uses the following protocol


HELO sending host
MAIL FROM:sender email address
RCPT TO: recipient email address
DATA
mail message

.
QUIT
 The email program uses a simple GUI to
input the required information
 The send button on the GUI calls the
sendMail() method which outputs the
correct protocol to the mail server
Socket s=new Socket(“engmail.bham.ac.uk”,25);
out=new PrintWriter(s.getOutputStream());
String hostname=InetAddress.getLocalHost().getHostName();
out.println(“HELO “ + hostname);
out.println(“MAIL FROM: “ + from.getText());
etc
URL connections
 We have seen that to send or retrieve information
to a web server, we use the HTTP protocol
through a client socket attached to port 80
 We can do this by using normal socket-based
programming and sending the correct HTTP
commands
 However, Java has specific support for the HTTP
protocol through its URLConnection class
 Its very easy to retrieve a file from a web server
by simply providing the file’s url as a string
URL u=new URL(“http://www.bham.ac.uk”);
URLConnection c=u.openConnection();
InputStream in=c.getInputStream();

 This sets up an input stream from a url connection


 Can turn this into a Scanner object for text
processing
 The URLConnection class also has additional
functionality related to the HTTP protocol
 Querying the server for header information

 Setting request properties


 The following simple example program
opens a web page and displays the HTML
 It also checks the server response code
 404 if the page is not found

 200 if the connection succeeded

 Uses a Scanner object to output the lines of


HTML
public class URLGet
{
public static void main(String[] args) throws IOException
{

String urlName;
if (args.length > 0)
urlName = args[0];
else
urlName = "http://java.sun.com";

URL url = new URL(urlName);


URLConnection c = url.openConnection();

// Check response code


HttpURLConnection httpConnection = (HttpURLConnection) c;
int code =httpConnection.getResponseCode();
String message=httpConnection.getResponseMessage();
System.out.println(code + " " + message);
if (code!=HttpURLConnection.HTTP_OK)
return;

// Read server response


InputStream instream=connection.getInputStream();
Scanner in=new Scanner(instream);
while (in.hasNextLine())
{
String input=in.nextLine();
System.out.println(input);
}
}
}
Advanced networking technologies
in Java
 In this section we will look briefly at more
advanced technologies for networking in
Java without looking in detail at code
 Sending data to a web server

 CGI and servlet technology

 Inter-object communication

 Remote method invocation (RMI)

 CORBA
CGI and servlet technology
 We often need to send data back to a web server
 Typically we fill out an online form displayed
on a web browser and click a ‘submit’ button
 Older web technology uses a CGI script to
process the information
 CGI stands for Common Gateway Interface

 Typically it is a program running on the


server and written in a scripting language
like Perl
 The CGI script processes the data submitted
and sends back a response to the client –
usually a HTML page
Script produces
reply page
Reply
page Client displays
web form
submit
CGI script

Form data

http server
Server starts Client web
CGI script Server returns browser
reply

Server
 CGI is well established and still widely used
technology
 Its major disadvantage is that each request
forks a new process which can make it slow
 Makes sharing resources tricky

 Also there are some security flaws with CGI


– it can be fooled into running commands
on the server since it uses an interpreted
scripted language
 Servlets are Java classes which extend the
HttpServlet class. They run inside a Servlet
Container which calls methods of the servlet
 The servlet container must be part of a

compliant web server which contains the Java


runtime environment
 They run in the Java virtual machine inside the
web server and so are portable and secure
 Unlike CGI each separate request creates a new

thread which is able to share resources with


existing running threads
Inter-object communication
 Object orientation is all about objects
‘communicating’ with each other by calling
each others’ methods
 What if the objects are distributed across

a network?
 What if the objects are implemented in
different languages? (eg Java and C++)
 There are two mechanisms for inter object
communication across a network
 Language independent mechanism is called
CORBA
 Common object request broker

 A separate language neutral broker object


handles all messages between the objects
 Generally rather slow and complex because
of its generality and ability to handle legacy
code
 If both objects are implemented in Java a much
simpler mechanism is Remote Method
Invocation (RMI)
 In RMI, a client object calls a method of a
server object on a different machine
 Client/server terminology only applies to
the single method call

Method call with parameters


Client Server
object object
Returned data (objects)
 All this seems easy but the actual behind the
scenes issues are complex
 Actual inter-object communictation is done
through separate stub objects which package
remote method calls and parameters
 The server registers its objects with a naming
service
 The clients finds the remote objects using a url :
“rmi://servername.com/”
 There are complex security issues involved also
as calling a remote method locally can
introduce viruses
 However, much of this is transparent to the
programmer and RMI is relatively straighforward
And finally…..
 Network programming is a doddle in Java
 Sockets look like ordinary I/O streams from
an application programming viewpoint
 The main issues are writing multi-threaded
code for multiple client applications
 In the last lab exercise, you will have the
opportunity to write a multi-threading
server for a network-based game!
A very early ……..

Merry Christmas!!

S-ar putea să vă placă și