240-322 Cli/Serv.: jnet/111 Client/Server Distributed Systems v Objectives –describe basic...

125
0-322 Cli/Serv.: jnet/11 Client/Server Distributed Syste Client/Server Distributed Syste ms ms Objectives Objectives describe basic networking in Java describe basic networking in Java Web page retrieval and sockets Web page retrieval and sockets programming programming 240-322, Semester 1, 2005-2006 11. Java Networking

Transcript of 240-322 Cli/Serv.: jnet/111 Client/Server Distributed Systems v Objectives –describe basic...

240-322 Cli/Serv.: jnet/11 1

Client/Server Distributed SystemsClient/Server Distributed Systems

ObjectivesObjectives– describe basic networking in Javadescribe basic networking in Java– Web page retrieval and sockets programmingWeb page retrieval and sockets programming

240-322, Semester 1, 2005-2006

11. Java Networking

240-322 Cli/Serv.: jnet/11 2

ContentsContents

1.1. Networking Restrictions in JavaNetworking Restrictions in Java

2.2. Basic Networking ClassesBasic Networking Classes

3.3. Sockets (Java Style)Sockets (Java Style)

4.4. Retrieving a Web PageRetrieving a Web Page– 4 different approaches 4 different approaches

5.5. A Stream Socket Client/ServerA Stream Socket Client/Server

continued

240-322 Cli/Serv.: jnet/11 3

6.6. A Datagram Socket A Datagram Socket Client/ServerClient/Server

7.7. Networked Tic-Tac-ToeNetworked Tic-Tac-Toe

8.8. More InformationMore Information

240-322 Cli/Serv.: jnet/11 4

1. Networking Restrictions in Java1. Networking Restrictions in Java

Many browsers place networking Many browsers place networking restrictions restrictions on appletson applets– usually communication is limited to being usually communication is limited to being

between your machine and the one where the between your machine and the one where the applet came fromapplet came from

There are There are no restrictions on Java applicationsno restrictions on Java applications or when using or when using appletviewerappletviewer

240-322 Cli/Serv.: jnet/11 5

Relaxing SecurityRelaxing Security

Applets can be Applets can be signedsigned with with trusted trusted certificatescertificates– a browser can be configured to relax security a browser can be configured to relax security

depending on an applet’s signaturedepending on an applet’s signature– an advanced topican advanced topic

240-322 Cli/Serv.: jnet/11 6

2. Basic Networking Classes2. Basic Networking Classes

The J2SE documentation for The J2SE documentation for java.netjava.net lists lists over 30 classes. A few of the key ones:over 30 classes. A few of the key ones:

InetAddressInetAddress

– the class that represents IP addresses and contaithe class that represents IP addresses and contains operations for manipulating them ns operations for manipulating them

see section 2.1see section 2.1

continued

240-322 Cli/Serv.: jnet/11 7

URLURL

– used to retrieve the Web page at the given URLused to retrieve the Web page at the given URL

URLConnectionURLConnection

– also used to retrieve a Web pagealso used to retrieve a Web page– allows extra parameters to be sent to the URLallows extra parameters to be sent to the URL

e.g HTTP request headerse.g HTTP request headers

continued

240-322 Cli/Serv.: jnet/11 8

SocketSocket– the client-side socket class for TCPthe client-side socket class for TCP

ServerSocketServerSocket– the server-side socket class for TCPthe server-side socket class for TCP

DatagramSocketDatagramSocket– allows a client or server to send/receive UDP paallows a client or server to send/receive UDP pa

cketsckets

240-322 Cli/Serv.: jnet/11 9

2.1. Finding an IP Address2.1. Finding an IP Address

Java’s Java’s InetAddressInetAddress class makes the mappin class makes the mapping between hostnames and IP addresses mucg between hostnames and IP addresses much easier than in UNIX.h easier than in UNIX.

For details, look at the the documentation foFor details, look at the the documentation for r java.net.InetAddressjava.net.InetAddress

240-322 Cli/Serv.: jnet/11 10

WhatIP.javaWhatIP.java

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

public class WhatIP { public static void main(String args[])

throws IOException { InetAddress addr =

InetAddress.getByName(args[0]); System.out.println("Inet address is "+ addr); } }

240-322 Cli/Serv.: jnet/11 11

UseUseCarried out from a DOS

prompt on my Windows machine.

240-322 Cli/Serv.: jnet/11 12

3. Sockets (Java Style)3. Sockets (Java Style) 1. Stream Sockets1. Stream Sockets

– the client/server connection exists for the entire the client/server connection exists for the entire duration of the request and answerduration of the request and answer

similar to a telephone callsimilar to a telephone call

– a a connection-oriented serviceconnection-oriented service corresponds to TCPcorresponds to TCP

– Java has separate classes for client and server Java has separate classes for client and server stream sockets (see section 5)stream sockets (see section 5)

240-322 Cli/Serv.: jnet/11 13

2. Datagram Sockets2. Datagram Sockets– the client/server send messages (the client/server send messages (packetspackets, ,

datagramsdatagrams) to each other) to each other similar to the postal servicesimilar to the postal service

– a a connectionless serviceconnectionless service corresponds to UDPcorresponds to UDP

– Java has classes for datagram sockets and Java has classes for datagram sockets and packets (see section 6).packets (see section 6).

240-322 Cli/Serv.: jnet/11 14

3.1. Pinging3.1. Pinging

pingping uses the ICMP protocol's uses the ICMP protocol's ECHO_REQUESTECHO_REQUEST datagram. Th datagram. The host’s answer is an ICMP e host’s answer is an ICMP ECHO_RESPONSEECHO_RESPONSE..

ping is a DOS command, not Java.

240-322 Cli/Serv.: jnet/11 15

ICMP packets can only be created via a socICMP packets can only be created via a socket of type ket of type SOCK_RAWSOCK_RAW..– but Java only supports but Java only supports SOCK_STREAMSOCK_STREAM (TCP) an (TCP) an

d d SOCK_DGRAMSOCK_DGRAM (UDP) sockets (UDP) sockets

Our solutionOur solution: use a TCP connection to the : use a TCP connection to the ddaytimeaytime service to pretend to ping service to pretend to ping– the daytime server listens at port 13the daytime server listens at port 13

240-322 Cli/Serv.: jnet/11 16

3.2. DayPing.java 3.2. DayPing.java JJJJ2, p.6772, p.677

import java.io.*;import java.net.*;public class DayPing {

public static void main(String args[]) throws Exception

{ if (args.length != 1) { System.out.println(

"Usage: java DayPing <machine name>"); System.exit(0); }

:

240-322 Cli/Serv.: jnet/11 17

String machine = args[0]; Socket so = new Socket(machine, 13); // daytime server listens at port 13

BufferedReader br = new BufferedReader(

new InputStreamReader( so.getInputStream() ) );

System.out.println( machine +

" is alive at " + br.readLine());

so.close(); } // end of main()

} // end of DayPing class

240-322 Cli/Serv.: jnet/11 18

DayPing.javaDayPing.java converts the socket connectio converts the socket connection into a n into a BufferedReaderBufferedReader

– this allows this allows readLine()readLine() to be used for socket in to be used for socket inputput

Using layered streams to add I/O functionaliUsing layered streams to add I/O functionality on top of sockets is a ty on top of sockets is a powerfulpowerful feature of feature of Java.Java.

NotesNotes

240-322 Cli/Serv.: jnet/11 19

UseUse C> javac DayPing.java

C> java DayPing calvincalvin is alive at Sat May 7 13:46:06 2005

C> java DayPing fourdotsException in thread "main" java.net.ConnectException: Connection refused: no further information at java.net.PlainSocketImpl.socketConnect

(Native Method) at java.net.PlainSocketImpl.doConnect... : at ping.main(DayPing.java:23)

All the examples were tested on my Windows machine

continued

240-322 Cli/Serv.: jnet/11 20

C> java DayPing takasillaException in thread "main" java.net.UnknownHostException: takasilla at java.net.PlainSocketImpl. connect(Unknown Source)

: at ping.main(DayPing.java:23)

C> java DayPing www.amazon.comException in thread "main" java.net.NoRouteToHostException: Operation timed out: connect at java.net.PlainSocketImpl.

socketConnect(Native Method):

at ping.main(DayPing.java:23)

After a long wait

After a wait

240-322 Cli/Serv.: jnet/11 21

3.3. Why Doesn't DayPing Work?3.3. Why Doesn't DayPing Work?

The examples that don't work show The examples that don't work show threethree di different errors:fferent errors:– ConnectExceptionConnectException– UnknownHostExceptionUnknownHostException– NoRouteToHostExceptionNoRouteToHostException

The "unknown host" exception is caused by The "unknown host" exception is caused by an incorrect IP address.an incorrect IP address.

continued

240-322 Cli/Serv.: jnet/11 22

The "connection" exception probably means that the server is uThe "connection" exception probably means that the server is unavailable (switched off)navailable (switched off)– this can be confirmed for a TCP service by trying to connect to it witthis can be confirmed for a TCP service by trying to connect to it wit

h h telnettelnet::

$ telnet fourdots 13$ telnet fourdots 13Trying 172.30.255.4...Trying 172.30.255.4...telnet: Unable to connect to remote host: Connection telnet: Unable to connect to remote host: Connection refusedrefused$ $

continued

executed from a differentmachine (fivedots)

240-322 Cli/Serv.: jnet/11 23

The "no route to host" exception usually meThe "no route to host" exception usually means that there is a ans that there is a firewallfirewall preventing the co preventing the connection from being made.nnection from being made.

telnettelnet response: response:$ telnet www.amazon.com 13$ telnet www.amazon.com 13Trying 207.171.163.90...Trying 207.171.163.90...telnet: Unable to connect to remote host: Cotelnet: Unable to connect to remote host: Connection nnection timed outtimed out$ $

A long wait,and then...

tried on (fivedots)

240-322 Cli/Serv.: jnet/11 24

3.4. Firewalls at PSU3.4. Firewalls at PSU

takasila

calvin

fivedots

Departmental firewall(no external socket creation; URLs allowed)

ratree

Univ. firewall(no external socket creation;

URLs only throughthe ‘cache’ proxy)

cache

The Internet

University

CoE Department

(simplified)

8080

240-322 Cli/Serv.: jnet/11 25

Ordinary users (i.e. students) cannot write Ordinary users (i.e. students) cannot write sockesocket-basedt-based programs that communicate outside PS programs that communicate outside PSUU– this is true in any language (Java, C, etc.)this is true in any language (Java, C, etc.)

ButBut programs can retrieve Web pages (and othe programs can retrieve Web pages (and other thingsr things) ) using the Java using the Java URLURL class class– the URL request must go through PSU's the URL request must go through PSU's cachecache mac mac

hinehine

240-322 Cli/Serv.: jnet/11 26

URLs and SocketsURLs and Sockets

From your data communications course, yoFrom your data communications course, you may recall that the Web protocol, HTTP, iu may recall that the Web protocol, HTTP, is built on top of TCP/IP.s built on top of TCP/IP.

Java's URL class uses stream sockets (TCP/Java's URL class uses stream sockets (TCP/IP) for its implementationIP) for its implementation– so why does it get past so why does it get past cachecache??

continued

240-322 Cli/Serv.: jnet/11 27

cachecache accepts socket links to valid Web ser accepts socket links to valid Web servers, but also checks that the HTTP GET (overs, but also checks that the HTTP GET (or POST) message includes additional valid r POST) message includes additional valid HTTP headers.HTTP headers.– all of this HTTP stuff is carried out by the URL all of this HTTP stuff is carried out by the URL

class for usclass for us

240-322 Cli/Serv.: jnet/11 28

4. Retrieving a Web Page4. Retrieving a Web Page

Five ways of obtaining a Web page:Five ways of obtaining a Web page:– 1. use a socket, and send a 1. use a socket, and send a GETGET message to the s message to the s

ervererver see see GetSocketPage.javaGetSocketPage.java

– 2. use a 2. use a URLURL object, and read the page via a stre object, and read the page via a streamam

see see GetURLPage.javaGetURLPage.java

continued

240-322 Cli/Serv.: jnet/11 29

– 3. use a 3. use a URLURL object, and display the page in a browser object, and display the page in a browser see see showPage.javashowPage.java

– 4. display a URL in an 4. display a URL in an JEditorPaneJEditorPane see see ShowURLPage.javaShowURLPage.java

– 5. use a HTTP URL connection, and send a 5. use a HTTP URL connection, and send a GETGET mess messageage

see Java’s networking tutorialsee Java’s networking tutorial

240-322 Cli/Serv.: jnet/11 30

4.1. Sockets and GET4.1. Sockets and GET GetSocketPage.javaGetSocketPage.java retrieves the page: retrieves the page:

http://<host name>/index.htmlhttp://<host name>/index.html

e.g.e.g. http://fivedots.coe.psu.ac.th/index.htmlhttp://fivedots.coe.psu.ac.th/index.html

It It printsprints the text of the page to the text of the page to stdoutstdout..

continued

240-322 Cli/Serv.: jnet/11 31

It opens a socket at port 80 for the host, whiIt opens a socket at port 80 for the host, which is the usually place where the Web servech is the usually place where the Web server is listening.r is listening.

It sends the HTTP It sends the HTTP GETGET message: message:GET /index.htmlGET /index.html

240-322 Cli/Serv.: jnet/11 32

DiagramDiagram

GetSocketPageclient host

Web server

GET /index.html

Web page (as text)

80

240-322 Cli/Serv.: jnet/11 33

GetSocketPage.javaGetSocketPage.java

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

public class GetSocketPage

{ public static void main(String args[])

throws IOException { Socket sock = new Socket(args[0],80);

:

240-322 Cli/Serv.: jnet/11 34

BufferedReader dis = new BufferedReader(

new InputStreamReader(

sock.getInputStream() )); PrintStream ps =

new PrintStream( sock.getOutputStream() );

ps.println("GET /index.html"); String line; while ((line = dis.readLine()) != null) System.out.println(line);

sock.close(); }} // end of GetSocketPage.java

240-322 Cli/Serv.: jnet/11 35

GetSocketPage.javaGetSocketPage.java converts the socket con converts the socket connection into a nection into a BufferedReaderBufferedReader for input, for input, andand a a PrintStreamPrintStream for output for output– uses uses readLine()readLine()for socket inputfor socket input– uses uses println()println() for socket output for socket output

NotesNotes

240-322 Cli/Serv.: jnet/11 36

UseUse

C> javac GetSocketPage.java

C> java GetSocketPage fivedots<html><head><title>Un title page</title></head><meta http-equiv="Content-Type" content="text/html; charset=windows-874"><style type="text/css"> :C>

text of Web page printed to stdout

240-322 Cli/Serv.: jnet/11 37

But... But...

C> java GetSocketPage www.amazon.comException in thread "main" java.net.ConnectExceException in thread "main" java.net.ConnectException: ption: Connection timed out: connect Connection timed out: connect at java.net.PlainSocketImpl.at java.net.PlainSocketImpl. socketConnect(Native Method) socketConnect(Native Method)

::at GetSocketPage.main(GetSocketPage.java:18)at GetSocketPage.main(GetSocketPage.java:18)

The firewall around PSUprevents Web serveraccess by sockets.

continued

240-322 Cli/Serv.: jnet/11 38

cache rejected the GET message to the extercache rejected the GET message to the external site since the message didn't include addnal site since the message didn't include additional HTTP headers.itional HTTP headers.

These can be supplied by us, but it's easier tThese can be supplied by us, but it's easier to use the URL class.o use the URL class.

240-322 Cli/Serv.: jnet/11 39

4.2. URL Object 4.2. URL Object

GetURLPage.javaGetURLPage.java avoids the firewall proble avoids the firewall problem with sockets by using a m with sockets by using a URLURL object. object.

A A URLURL object allows a Web page to be retrie object allows a Web page to be retrieved as a stream of textved as a stream of text– our program prints the text to our program prints the text to stdoutstdout..

240-322 Cli/Serv.: jnet/11 40

GetURLPage.javaGetURLPage.java

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

public class GetURLPage { public static void main(String args[]) { try { URL url = new URL(args[0]); BufferedReader dis =

new BufferedReader(new InputStreamReader(

url.openStream() ));:

240-322 Cli/Serv.: jnet/11 41

String line; while ( (line = dis.readLine()) != null ) System.out.println(line);

dis.close(); } catch (Exception e) { System.out.println(e); } }

} // end of GetURLPage.java

240-322 Cli/Serv.: jnet/11 42

A stream for the A stream for the URLURL object is obtained usin object is obtained using g openStream()openStream()

– after that the same input stream layering techniafter that the same input stream layering technique is used as in que is used as in GetSocketPage.javaGetSocketPage.java

– there is no need to send a there is no need to send a GETGET message message

NotesNotes

240-322 Cli/Serv.: jnet/11 43

UseUse C> javac GetURLPage.java C> java GetURLPage http://www.amazon.co.uk

java.net.ConnectException: Connection timed out: connect

C> java -DproxySet=true -DproxyHost=cache.psu.ac.th -DproxyPort=8080

GetURLPage http://www.amazon.com/<html><head><title>Amazon Page</title></head><body bgcolor=#ffffff test=#000000><H1> :C>

typed onone line

after along wait

240-322 Cli/Serv.: jnet/11 44

Ordinary users can access outside PSU by uOrdinary users can access outside PSU by using URLs, but they must route their requestsing URLs, but they must route their requests via PSU s via PSU cachecache machine. machine.

240-322 Cli/Serv.: jnet/11 45

Batch Files for Long CommandsBatch Files for Long Commands

GetURLPage.batGetURLPage.bat contains: contains:@echo offecho Executing GetURLPage...java -DproxySet=true -DproxyHost=cache.psu.ac.th -DproxyPort=8080 GetURLPage %1

Use:Use:c> GetURLPage http://www.amazon.co.uk : // same output as last slide

240-322 Cli/Serv.: jnet/11 46

Proxy Username/PasswordProxy Username/Password

A further level of firewall security is to requA further level of firewall security is to require the user to enter a username and passworire the user to enter a username and passwordd– called called proxy authorizationproxy authorization

Java has network support for authorizationJava has network support for authorization– it allows a username and password to be sent by it allows a username and password to be sent by

a client program to the firewalla client program to the firewall

continued

240-322 Cli/Serv.: jnet/11 47

A good tutorial:A good tutorial:– ““Jump a Proxy/Firewall and Live to Tell About it”Jump a Proxy/Firewall and Live to Tell About it”http://www.devx.com/upload/free/features/http://www.devx.com/upload/free/features/javapro/2000/03mar00/te0003/te0003.aspjavapro/2000/03mar00/te0003/te0003.asp

Slightly modified code is in Slightly modified code is in GetThroughProxy.javaGetThroughProxy.java at:at:http://fivedots.coe.psu.ac.th/http://fivedots.coe.psu.ac.th/ Software.coe/Cliserv/ Software.coe/Cliserv/ Code%20Examples/Java%20Code/ Code%20Examples/Java%20Code/ Basic%20Networking/ Basic%20Networking/

240-322 Cli/Serv.: jnet/11 48

4.3. Passing a URL to a Browser4.3. Passing a URL to a Browser

If the Java code is in an applet, then the doIf the Java code is in an applet, then the downloaded URL can be displayed in the brownloaded URL can be displayed in the browser.wser.

showPage.htmlshowPage.html displays a user-specified We displays a user-specified Web page in the (Opera) browser, using the b page in the (Opera) browser, using the ShoSho

wPage.javawPage.java applet. applet.

240-322 Cli/Serv.: jnet/11 49

UsageUsage

continued

The dialog box appears in frontof the browser window.

240-322 Cli/Serv.: jnet/11 50

Loaded Page:

240-322 Cli/Serv.: jnet/11 51

showPage.htmlshowPage.html

<html><head><html><head><title>Web Page Loading Applet</title></head><title>Web Page Loading Applet</title></head><body><body><h1>Web Page Loading Applet</h1><h1>Web Page Loading Applet</h1><P>Applet is placed here... <P>Applet is placed here... <applet code="ShowPage.class"<applet code="ShowPage.class"

width=300 height=50>width=300 height=50></applet></applet></P></P></body></html></body></html>

240-322 Cli/Serv.: jnet/11 52

showPage.javashowPage.java

import java.net.*;import java.net.*;import javax.swing.*;import javax.swing.*;import java.applet.AppletContext;import java.applet.AppletContext;import javax.swing.JOptionPane;import javax.swing.JOptionPane;

public class ShowPage extends JApplet public class ShowPage extends JApplet {{ public void init() public void init() { { try { try {

String urlString = String urlString = JOptionPane.showInputDialog( JOptionPane.showInputDialog(

"Enter a URL:");"Enter a URL:"); URL url = new URL(urlString);URL url = new URL(urlString);

::

240-322 Cli/Serv.: jnet/11 53

AppletContext browser = getAppletContext();AppletContext browser = getAppletContext(); browser.showDocument(url); browser.showDocument(url);

} } catch (Exception e) catch (Exception e) { System.out.println(e); }{ System.out.println(e); }

} // end of init() } // end of init()

} // end of ShowPage} // end of ShowPage

240-322 Cli/Serv.: jnet/11 54

NotesNotes

The download only works because the browThe download only works because the browser is set up to work through ser is set up to work through cachecache..

There are no Java security restrictions on a There are no Java security restrictions on a applet passing a URL to a browser to be disapplet passing a URL to a browser to be displayed.played.

continued

240-322 Cli/Serv.: jnet/11 55

A URL is downloaded with A URL is downloaded with showDocument()showDocument(), , which must be called in the applet’s which must be called in the applet’s environment (i.e. the browser):environment (i.e. the browser):– AppletContext browser = AppletContext browser =

getAppletContext();getAppletContext(); browser.showDocument(url);browser.showDocument(url);

The URL is automatically loaded into the The URL is automatically loaded into the browser, replacing browser, replacing showPage.htmlshowPage.html..

continued

240-322 Cli/Serv.: jnet/11 56

There is a two-argument version of There is a two-argument version of showDocument()showDocument() that can load URLs into that can load URLs into frames.frames.

D&D contains a more complex example D&D contains a more complex example ((SiteSelector.javaSiteSelector.java, ch. 21) which allows , ch. 21) which allows the user to select a URL from a list.the user to select a URL from a list.

240-322 Cli/Serv.: jnet/11 57

4.4. Displaying a URL with JEditorPane4.4. Displaying a URL with JEditorPane

The Swing GUI includes The Swing GUI includes JEditorPaneJEditorPane whic which allows 'structured' text to be displayed and h allows 'structured' text to be displayed and edited.edited.– offers basic support for plain text, RTF, and offers basic support for plain text, RTF, and HTHT

MLML– see see javax.swing.JEditorPanejavax.swing.JEditorPane

continued

240-322 Cli/Serv.: jnet/11 58

A A JEditorPaneJEditorPane can be filled by calling can be filled by calling setPsetP

age()age() with a with a URL string argumentURL string argument..

JEditorPaneJEditorPane also has support for capturing also has support for capturing hyperlink clicks as events.hyperlink clicks as events.

continued

240-322 Cli/Serv.: jnet/11 59

With these features, it is possible to write a basiWith these features, it is possible to write a basic Web browser!c Web browser!

ShowURLPage.javaShowURLPage.java has a text field for the user to has a text field for the user to enter a URLenter a URL– the resulting downloaded page is displayed in a the resulting downloaded page is displayed in a JEdJEd

itorPaneitorPane – if a link is clicked inside the pane, then its page will if a link is clicked inside the pane, then its page will

be loaded automaticallybe loaded automatically

continued

240-322 Cli/Serv.: jnet/11 60

I clicked on “School of Advanced...”

240-322 Cli/Serv.: jnet/11 61

ShowURLPage’s Event ModelShowURLPage’s Event Model

enter

contents

X

hyperlinkUpdate() {...}

GUI

CodeactionPerformed() {...}

hyperlinkevents

actionevents

^

^

240-322 Cli/Serv.: jnet/11 62

ShowURLPage.javaShowURLPage.java

import java.awt.*;import java.awt.event.*;import java.net.*;import java.io.*;import javax.swing.*;import javax.swing.event.*;

public class ShowURLPage extends JFrame { private JTextField enter; private JEditorPane contents;

:

240-322 Cli/Serv.: jnet/11 63

public ShowURLPage() { super("Simple Web Browser"); Container c = getContentPane();

enter = new JTextField("Enter file URL here");

enter.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e ) { getPage(e.getActionCommand());} });

c.add(enter, BorderLayout.NORTH);:

240-322 Cli/Serv.: jnet/11 64

contents = new JEditorPane(); contents.setEditable(false);

contents.addHyperlinkListener( new HyperlinkListener() { public void hyperlinkUpdate(

HyperlinkEvent e) { if(e.getEventType() ==

HyperlinkEvent.EventType.ACTIVATED) getPage(e.getURL().toString()); } });

:

240-322 Cli/Serv.: jnet/11 65

c.add( new JScrollPane(contents), BorderLayout.CENTER);

setDefaultCloseOperation( JFrame.EXIT_ON_CLOSE); setSize(400, 300); setVisible(true); } // end of ShowURLPage()

240-322 Cli/Serv.: jnet/11 66

private void getPage(String location) { setCursor(Cursor.getPredefinedCursor( Cursor.WAIT_CURSOR)); try { contents.setPage(location); enter.setText(location); } catch (IOException io) { JOptionPane.showMessageDialog(this, "Error retrieving specified URL", "Bad URL", JOptionPane.ERROR_MESSAGE); } setCursor( Cursor.getPredefinedCursor( Cursor.DEFAULT_CURSOR) ); } // end of getPage()

240-322 Cli/Serv.: jnet/11 67

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

} // end of ShowURLPage class

240-322 Cli/Serv.: jnet/11 68

UseUse

C> javac ShowURLPage.java

C> java ShowURLPage// A request for http://www.cs.ait.ac.th/~ad// causes a “Bad URL” dialog box to appear

C> java -DproxySet=true -DproxyHost=cache.psu.ac.th -DproxyPort=8080 ShowURLPage

Typed all on one line.The window shown on the left of slide 60 appears.

240-322 Cli/Serv.: jnet/11 69

NotesNotes

The The JEditorPaneJEditorPane must be set uneditable so must be set uneditable so that hyperlinks events can be captured.that hyperlinks events can be captured.

Hyperlink events include: Hyperlink events include: ENTEREDENTERED, , EXITEDEXITED, , and and ACTIVATEDACTIVATED..– see see javax.swing.event.HyperlinkEventjavax.swing.event.HyperlinkEvent

continued

240-322 Cli/Serv.: jnet/11 70

getPage()getPage() calls calls setPage()setPage() to display a URL to display a URL in the in the JEditorPaneJEditorPane – the call is surrounded by changes to the cursor ithe call is surrounded by changes to the cursor i

con so things look busycon so things look busy

getPage()getPage() is called in two possible ways: is called in two possible ways:– as a response to pressing enter in the textfieldas a response to pressing enter in the textfield– as a response to a link being clickedas a response to a link being clicked

240-322 Cli/Serv.: jnet/11 71

5. A Stream Socket Client/Server5. A Stream Socket Client/Server

AlienClient.java AlienServer1.java

socket Server socket

socketfor clientcomms.

4444

the new socket is made with accept()

Initial Internet connection

input andoutputstreams

input andoutputstreams

240-322 Cli/Serv.: jnet/11 72

The server creates a new socket when a client The server creates a new socket when a client contacts itcontacts it– client/server communication via the new socketclient/server communication via the new socket

– this frees up the main server socket to receive this frees up the main server socket to receive connections from other clientsconnections from other clients

– AlienServer1.javaAlienServer1.java is an is an iterative serveriterative server it can only process one client at a timeit can only process one client at a time

continued

240-322 Cli/Serv.: jnet/11 73

Our client and server both run on Our client and server both run on localhostlocalhost..

AlienServer1AlienServer1 actions: actions:– wait for a client connectionwait for a client connection– after a connection, wait for a message from the after a connection, wait for a message from the

clientclient– respond depending on the content of the messagerespond depending on the content of the message– close the client connection, and loop, waiting for close the client connection, and loop, waiting for

another clientanother client

continued

240-322 Cli/Serv.: jnet/11 74

Diagram for Client ProcessingDiagram for Client Processing

AlienClient.java AlienServer1.java1. send message

4. send answer2. analyse message3. print message locally

5. close socket

240-322 Cli/Serv.: jnet/11 75

AlienServer1.javaAlienServer1.java

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

public class AlienServer1 { public static void main(String args[])

throws IOException { Socket sock; BufferedReader in; PrintStream out;

ServerSocket servsock = new ServerSocket(4444);

:

240-322 Cli/Serv.: jnet/11 76

while (true) { // wait for the next client connection sock = servsock.accept();

// Get I/O streams from the socket out = new PrintStream(

sock.getOutputStream() ); in = new BufferedReader(

new InputStreamReader( sock.getInputStream() ) );

:

240-322 Cli/Serv.: jnet/11 77

// get client message and respond String msg = in.readLine(); System.out.println(" Received: " + msg);

if (msg.indexOf("hello") > -1) { System.out.println(" Friendly contact made"); out.println("Welcome friend"); } else {

System.out.println(" Probably an alien"); out.println("ET go home"); } out.flush();

// Close this connection, // (not the overall server socket)

sock.close(); } } // of main()}// end of AlienServer1

240-322 Cli/Serv.: jnet/11 78

The client: AlienClient.javaThe client: AlienClient.java

AlienClient.javaAlienClient.java’s actions:’s actions:– open a connection with the serveropen a connection with the server– send a message taken from the command linesend a message taken from the command line– receive and print the server’s responsereceive and print the server’s response– closeclose

240-322 Cli/Serv.: jnet/11 79

AlienClient.javaAlienClient.java

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

public class AlienClient { public static void main(String args[])

throws IOException { Socket sock = new Socket("localhost", 4444); // Get I/O streams from the socket BufferedReader br =

new BufferedReader( new InputStreamReader(

sock.getInputStream()) ); PrintStream ps = new PrintStream(

sock.getOutputStream() );:

240-322 Cli/Serv.: jnet/11 80

// Send a message from the command line ps.println(args[0]); ps.flush();

// Read server’s response String line = br.readLine(); System.out.println( "Got this from server:\n " + line);

sock.close(); } // end of main()

} // end of AlienClient class

240-322 Cli/Serv.: jnet/11 81

UseUse

Client: Server:

I used two separate DOS windowson the same machine.

240-322 Cli/Serv.: jnet/11 82

Telnet Client (from fivedots)Telnet Client (from fivedots)

Server:

I typed this

240-322 Cli/Serv.: jnet/11 83

A More Complex ExampleA More Complex Example

D&D gives a larger stream socket client/servD&D gives a larger stream socket client/server example (ch. 21):er example (ch. 21):– object input and output streamsobject input and output streams are used are used

– the sequence of communication is more complex the sequence of communication is more complex the client maintains a long-lived link with the server uthe client maintains a long-lived link with the server u

ntil it sends a “TERMINATE” stringntil it sends a “TERMINATE” string

240-322 Cli/Serv.: jnet/11 84

5.1. A Concurrent Server5.1. A Concurrent Server

AlienServer2.javaAlienServer2.java uses uses threadsthreads to handle to handle multiple clients concurrently.multiple clients concurrently.

Three main advantages:Three main advantages:– the server code is simpler since server processinthe server code is simpler since server processin

g is in a separate class called g is in a separate class called WorkerWorker

– clients do not have to wait clients do not have to wait – the server is more scaleablethe server is more scaleable

240-322 Cli/Serv.: jnet/11 85

AlienServer2 VisuallyAlienServer2 Visually

AlienServer2AlienClient clients 4444

Workerthreads

each Worker thread can deal with multiple messages from its client

240-322 Cli/Serv.: jnet/11 86

5.2. Java Threads (Briefly)5.2. Java Threads (Briefly)

There are There are two ways to create a threadtwo ways to create a thread::– extend the extend the ThreadThread class class– write a class to implement the write a class to implement the RunnableRunnable interfa interfa

cece

We use the first approach since We use the first approach since WorkerWorker doe does not need to extend any other classes.s not need to extend any other classes.

continued

240-322 Cli/Serv.: jnet/11 87

A class extended from A class extended from ThreadThread must define the must define the rrun()un() method: method:

class Worker extends Thread {class Worker extends Thread { public void run() public void run() { ... } { ... }

}}

A threaded object is started by calling A threaded object is started by calling start()start():: Worker w = new Worker(...):Worker w = new Worker(...):

w.start();w.start();

The thread will call The thread will call run()run() itself from within itself from within stasta

rt()rt()..

240-322 Cli/Serv.: jnet/11 88

5.3. AlienServer2.java5.3. AlienServer2.java

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

public class Worker extends Thread { private Socket sock; private int id;

public Worker(Socket s, int c) { sock = s; id = c; }

:

240-322 Cli/Serv.: jnet/11 89

public void run() { // Get I/O streams from the socket try { PrintStream out = new PrintStream(

sock.getOutputStream() ); BufferedReader in = new BufferedReader(

new InputStreamReader(

sock.getInputStream() )); :

240-322 Cli/Serv.: jnet/11 90

// get client messages and respond String msg; while ((msg = in.readLine()) != null) { System.out.println(" Worker "+id+ " received: "+ msg); if (msg.indexOf("hello") > -1) out.println("Welcome friend") else out.println("ET go home"); out.flush(); } :

The worker contains much the same client processing code as the iterative server.

240-322 Cli/Serv.: jnet/11 91

// Close this connection, // (not the overall server socket)

System.out.println(" Worker " + id + " finished"); sock.close(); } catch(IOException ioe) {System.out.println(ioe); } } // end of run()

} // end of Worker class

240-322 Cli/Serv.: jnet/11 92

public class AlienServer2 { public static void main(String args[])

throws IOException { Socket sock; ServerSocket servsock =

new ServerSocket(4444, 6);

while (true) { // wait for the next client connection sock = servsock.accept(); new Worker(sock).start(); } } // of main()} // of AlienServer2 class

240-322 Cli/Serv.: jnet/11 93

UseUseServer:

240-322 Cli/Serv.: jnet/11 94

Client on fivedotsClient on fivedots

240-322 Cli/Serv.: jnet/11 95

Two Local Clients (one closed)Two Local Clients (one closed)

240-322 Cli/Serv.: jnet/11 96

6. A Datagram Socket Client/Server6. A Datagram Socket Client/Server

UDPClient UDPServer

Datagramsocket

5000Datagramsocket

any port msg

packets

echo

240-322 Cli/Serv.: jnet/11 97

6.1. Server Event Model6.1. Server Event Model

display

X GUI

Code

^

^

packet2) echo back

to client

waitForPackets() {...}

packet

1) receive fromclient

240-322 Cli/Serv.: jnet/11 98

6.2. UDPServer.java6.2. UDPServer.java

import java.io.*;import java.net.*;import java.awt.*;import java.awt.event.*;import javax.swing.*;

public class UDPServer extends JFrame { private JTextArea display;

:

240-322 Cli/Serv.: jnet/11 99

public UDPServer() { super("UDP Server");

display = new JTextArea(); getContentPane().add(

new JScrollPane( display), BorderLayout.CENTER ); setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); setSize(400, 300); show(); DatagramSocket socket = null; try { socket = new DatagramSocket( 5000 ); } catch(SocketException se) { se.printStackTrace(); System.exit(1); } waitForPackets(socket); } // end of UDPServer()

240-322 Cli/Serv.: jnet/11 100

private void waitForPackets(DatagramSocket socket) { DatagramPacket sendPacket, receivePacket;

while (true) { try { // set up packet data structure byte data[] = new byte[100]; receivePacket = new DatagramPacket(data, data.length);

// wait for packet from client socket.receive(receivePacket);

:

240-322 Cli/Serv.: jnet/11 101

// process client packet display.append("\nPacket received:" + "\nFrom host: "+receivePacket.getAddress()+ "\nHost port: " + receivePacket.getPort() + "\nLength: " + receivePacket.getLength() + "\nContaining:\n\t" + new String(receivePacket.getData(), 0, receivePacket.getLength()));

:

240-322 Cli/Serv.: jnet/11 102

// echo packet info back to client display.append(

"\n\nEcho data to client..."); sendPacket = new DatagramPacket(

receivePacket.getData(), receivePacket.getLength(), receivePacket.getAddress(), receivePacket.getPort() ); socket.send( sendPacket ); display.append("Packet sent\n"); display.setCaretPosition( display.getText().length() ); }

:

240-322 Cli/Serv.: jnet/11 103

catch(IOException io) { display.append(io.toString() + "\n"); io.printStackTrace(); } } } // end of waitForPackets{}

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

} // end of UDPServer

240-322 Cli/Serv.: jnet/11 104

Server NotesServer Notes

The server creates one datagram socket at The server creates one datagram socket at port 5000:port 5000:

socket = new DatagramSocket(5000);socket = new DatagramSocket(5000);

Datagram socket creation must be inside a Datagram socket creation must be inside a try/catch block.try/catch block.

continued

240-322 Cli/Serv.: jnet/11 105

The server loops inside The server loops inside waitForPackets()waitForPackets()

– creates an empty packet (100 bytes long)creates an empty packet (100 bytes long)– blocks inside blocks inside receive()receive()

When When receive()receive() returns, the packet returns, the packet contains data and:contains data and:– the Internet address of the senderthe Internet address of the sender– the port number of the senderthe port number of the sender– the actual length of the datathe actual length of the data

continued

240-322 Cli/Serv.: jnet/11 106

The packet information can be accessed via The packet information can be accessed via methods. e.g.:methods. e.g.:

receivePacket.getPort();receivePacket.getPort(); receivePacket.getData(); receivePacket.getData();

receive()receive() must be in a try/catch block. must be in a try/catch block.

continued

240-322 Cli/Serv.: jnet/11 107

The server echoes the datagram back to the The server echoes the datagram back to the client at the address and port obtained from the client at the address and port obtained from the client’s message:client’s message:

sendPacket = new DatagramPacket(sendPacket = new DatagramPacket(receivePacket.getData(),receivePacket.getData(),receivePacket.getLength(), receivePacket.getLength(), receivePacket.getAddress(),receivePacket.getAddress(),receivePacket.getPort() );receivePacket.getPort() );

socket.send(sendPacket); socket.send(sendPacket);

send()send() must be in a try/catch block. must be in a try/catch block.

240-322 Cli/Serv.: jnet/11 108

6.3. Client Event Model6.3. Client Event Model

enter

display

XGUI

CodeactionPerformed() {...}

actionevents

^^

packet

1) send to server

waitForPackets() {...}

packet2) receive echo

from sender

240-322 Cli/Serv.: jnet/11 109

6.4. UDPClient.java6.4. UDPClient.java

import java.io.*;import java.net.*;import java.awt.*;import java.awt.event.*;import javax.swing.*;

public class UDPClient extends JFrame implements ActionListener

{ private JTextField enter; private JTextArea display;

private DatagramSocket socket;:

240-322 Cli/Serv.: jnet/11 110

public UDPClient() { super("UDP Client");

enter = new JTextField("Type message here"); enter.addActionListener(this); getContentPane().add(enter,BorderLayout.NORTH);

display = new JTextArea(); getContentPane().add(new JScrollPane(display), BorderLayout.CENTER); setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); setSize(400, 300); setVisible(true);

:

240-322 Cli/Serv.: jnet/11 111

try { socket = new DatagramSocket(); } catch(SocketException se) { se.printStackTrace(); System.exit(1); }

waitForPackets(); } // end of UDPClient()

240-322 Cli/Serv.: jnet/11 112

private void waitForPackets() { DatagramPacket receivePacket;

while (true) { try { // set up packet data structure byte data[] = new byte[100]; receivePacket = new DatagramPacket(data, data.length);

// wait for packet from server socket.receive(receivePacket);

:

240-322 Cli/Serv.: jnet/11 113

// process packet from server display.append("\nPacket received:" + "\nFrom host: "+receivePacket.getAddress()+ "\nHost port: " + receivePacket.getPort() + "\nLength: " + receivePacket.getLength() + "\nContaining:\n\t" + new String( receivePacket.getData(), 0, receivePacket.getLength())); display.setCaretPosition( display.getText().length() ); } catch(IOException ex) { display.append(ex.toString()+"\n" ); ex.printStackTrace(); } } } // end of waitForPackets()

240-322 Cli/Serv.: jnet/11 114

public void actionPerformed(ActionEvent e) { DatagramPacket sendPacket; try { display.append(

"\nSending packet containing: " + e.getActionCommand() + "\n" );

String s = e.getActionCommand(); byte data[] = s.getBytes();

sendPacket = new DatagramPacket( data, data.length,

InetAddress.getLocalHost(), 5000); socket.send(sendPacket);

:

240-322 Cli/Serv.: jnet/11 115

display.append("Packet sent\n"); display.setCaretPosition( display.getText().length() ); } catch (IOException ex) { display.append(ex.toString()+"\n"); ex.printStackTrace(); } } // end of actionPerformed()

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

} // end of UDPClient

240-322 Cli/Serv.: jnet/11 116

Client NotesClient Notes

The client gets the data for each packet The client gets the data for each packet from the user entering a string into a from the user entering a string into a TextFieldTextField..

The client creates a datagram socket with The client creates a datagram socket with no specified port number:no specified port number:

socket = new DatagramSocket();

continued

240-322 Cli/Serv.: jnet/11 117

In In actionPerformed()actionPerformed(), the user’s input is , the user’s input is converted into a packet, and sent to the server:converted into a packet, and sent to the server:

sendPacket = new DatagramPacket(data, data.length(),InetAddress.getLocalHost(), 5000);

socket.send(sendPacket);

The code assumes that the server is on the same The code assumes that the server is on the same machine as the client, and attached to port 5000.machine as the client, and attached to port 5000.

continued

240-322 Cli/Serv.: jnet/11 118

The client receives the echoed reply in The client receives the echoed reply in waitForPackets()waitForPackets()::– the loop blocks inside the loop blocks inside receive()receive() until a packet until a packet

arrives from the serverarrives from the server– the packet details are displayed in the the packet details are displayed in the JTextAreaJTextArea

The blocked The blocked waitForPackets()waitForPackets() does not stop does not stop the user from entering more strings for the the user from entering more strings for the client to send outclient to send out– the GUI always runs in a separate threadthe GUI always runs in a separate thread

240-322 Cli/Serv.: jnet/11 119

6.5. Use6.5. Use

continued

1. message sent to server

3. Echoed messagereceived from the server

2. Client messagereceived and echoed

Tested by starting the client and server intwo separate DOS windows.

240-322 Cli/Serv.: jnet/11 120

Another message sent and echoed back:

240-322 Cli/Serv.: jnet/11 121

7. Networked Tic-Tac-Toe7. Networked Tic-Tac-ToeD&D Section 21.8, p.1031

thread

thread

5000

synchronizedvalidMove()

thread

Client: Player ‘X’

Server

data

thread

Client: Player ‘O’

data

240-322 Cli/Serv.: jnet/11 122

OutputOutput p.1041-1042 p.1041-1042

240-322 Cli/Serv.: jnet/11 123

8. More Information8. More Information

Chapter 21, Deitel & Deitel (D&D)Chapter 21, Deitel & Deitel (D&D)http://java.coe.psu.ac.th/ForMember/http://java.coe.psu.ac.th/ForMember/ Books.html#Network Books.html#Network

Killer Game Programming in JavaKiller Game Programming in JavaChapter 29, Network BasicsChapter 29, Network Basicshttp://fivedots.coe.psu.ac.th/~ad/jg/ch18/

240-322 Cli/Serv.: jnet/11 124

Core Java 2, Vol II - Advanced FeaturesCore Java 2, Vol II - Advanced FeaturesCay S. Horstmann & Gary CornellCay S. Horstmann & Gary CornellSun Microsystems Press, 2001,Sun Microsystems Press, 2001,chapter 3chapter 3– multithreaded server, sending e-mail, URLConmultithreaded server, sending e-mail, URLCon

nection, HTTP POSTnection, HTTP POST– http://java.coe.psu.ac.th/ForMember/http://java.coe.psu.ac.th/ForMember/ Books.html#Network Books.html#Network

240-322 Cli/Serv.: jnet/11 125

Aj. Somchai's Java SiteAj. Somchai's Java Site– Network and Distributed Programming BooksNetwork and Distributed Programming Bookshttp://java.coe.psu.ac.th/ForMember/http://java.coe.psu.ac.th/ForMember/ Books.html#Network Books.html#Network