240-322 Cli/Serv.: jnet/111 Client/Server Distributed Systems v Objectives –describe basic networking in Java – Web page retrieval and sockets programming.

Slides:



Advertisements
Similar presentations
Multiplexing/Demux. CPSC Transport Layer 3-2 Multiplexing/demultiplexing application transport network link physical P1 application transport network.
Advertisements

Network Programming Chapter 11 Lecture 6. Networks.
Liang, Introduction to Java Programming, Fifth Edition, (c) 2005 Pearson Education, Inc. All rights reserved Chapter 25 Networking.
1 Frameworks. 2 Framework Set of cooperating classes/interfaces –Structure essential mechanisms of a problem domain –Programmer can extend framework classes,
2: Application Layer 1 Socket programming Socket API r introduced in BSD4.1 UNIX, 1981 r explicitly created, used, released by apps r client/server paradigm.
1 Java Networking – Part I CS , Spring 2008/9.
CS 491, 591 Networking in Java Summer Establishing a Simple Server (Using Stream Sockets) Creating a Java server –Create ServerSocket object ServerSocket.
1 L52 Networking (1). 2 OBJECTIVES In this chapter you will learn:  To understand Java networking with URLs, sockets and datagrams.  To implement Java.
Programming Applets How do Applets work ? This is an HTML page This is the applet’s code It has a link to an applet.
 Pearson Education, Inc. All rights reserved. 1 CH24 Networking : OBJECTIVES In this chapter you will learn:  To understand Java networking.
1 Overview r Socket programming with TCP r Socket programming with UDP r Building a Web server.
Liang, Introduction to Java Programming, Sixth Edition, (c) 2007 Pearson Education, Inc. All rights reserved L24 (Chapter 25) Networking.
CIS – Spring Instructors: Geoffrey Fox, Bryan Carpenter Computational Science and.
28-Jun-15 Basic Protocols. 2 Sockets Sockets, or ports, are a very low level software construct that allows computers to talk to one another When you.
2: Application Layer1 Socket Programming. 2: Application Layer2 Socket-programming using TCP Socket: a door between application process and end- end-transport.
Liang, Introduction to Java Programming, Sixth Edition, (c) 2007 Pearson Education, Inc. All rights reserved Chapter 25 Networking.
1 Network Layers Application Transport Network Data-Link Physical bits.
15-Jul-15 Basic Protocols. 2 Sockets Sockets, or ports, are a very low level software construct that allows computers to talk to one another When you.
Io package as Java’s basic I/O system continue’d.
2: Application Layer 1 Socket Programming TCP and UDP.
JAVA Socket Programming Source: by Joonbok Lee, KAIST, 2003.
Babak Esfandiari (based on slides by Qusay Mahmoud)
CS4273: Distributed System Technologies and Programming I Lecture 5: Java Socket Programming.
SOCKET PROGRAMMING. Client/Server Communication At a basic level, network-based systems consist of a server, client, and a media for communication as.
TCP/IP protocols Communication over Internet is mostly TCP/IP (Transmission Control Protocol over Internet Protocol) TCP/IP "stack" is software which allows.
2: Application Layer1 Chapter 2: Application layer r 2.1 Principles of network applications r 2.2 Web and HTTP r 2.3 FTP r 2.4 Electronic Mail  SMTP,
2: Application Layer1 Socket programming Socket API r introduced in BSD4.1 UNIX, 1981 r explicitly created, used, released by apps r client/server paradigm.
An program As a simple example of socket programming we can implement a program that sends to a remote site As a simple example of socket.
 Socket  The combination of an IP address and a port number. (RFC 793 original TCP specification)  The name of the Berkeley-derived application programming.
Cli/Serv.: Chat/121 Client/Server Distributed Systems v Objectives –discuss a client/server based chat system –mention two other ways of chatting.
-1- Georgia State UniversitySensorweb Research Laboratory CSC4220/6220 Computer Networks Dr. WenZhan Song Associate Professor, Computer Science.
REVIEW On Friday we explored Client-Server Applications with Sockets. Servers must create a ServerSocket object on a specific Port #. They then can wait.
Socket Programming Lee, Sooyong
Network Programming and Sockets CPSC 363 Computer Networks Ellen Walker Hiram College (Includes figures from Computer Networking by Kurose & Ross, © Addison.
Socket Programming Tutorial. Socket programming Socket API introduced in BSD4.1 UNIX, 1981 explicitly created, used, released by apps client/server paradigm.
Practicum: - Client-Server Computing in Java Fundamental Data Structures and Algorithms Margaret Reid-Miller 13 April 2004.
Object Oriented Programming in Java Lecture 16. Networking in Java Concepts Technicalities in java.
1 Chapter 28 Networking. 2 Objectives F To comprehend socket-based communication in Java (§28.2). F To understand client/server computing (§28.2). F To.
1 Network Programming and Java Sockets. 2 Network Request Result a client, a server, and network Client Server Client machine Server machine Elements.
L 2 - 1 3( 1/ 20) : Java Network Programming. The Socket API The previous contents describe client-server interaction that application programs use when.
 2003 Joel C. Adams. All Rights Reserved. Calvin CollegeDept of Computer Science(1/11) Java Sockets and Simple Networking Joel Adams and Jeremy Frens.
CS390- Unix Programming Environment CS 390 Unix Programming Environment Java Socket Programming.
2: Application Layer1 Socket programming Socket API Explicitly created, used, released by apps Client/server paradigm Two types of transport service via.
1 CSCD 330 Network Programming Spring 2014 Some Material in these slides from J.F Kurose and K.W. Ross All material copyright Lecture 7 Application.
Part 4: Network Applications Client-server interaction, example applications.
1 Applets. 2 Design of Applets 3 Sun wrote Java to be executable within a hosting application browser The applications are applets. An applet is downloaded.
CIS Intro to JAVA Lecture Notes Set July-05 GUI Programming –TextField Action Listeners, JEditorPane action listeners, HTML in a JEditorPane,
1 Socket programming Socket API r introduced in BSD4.1 UNIX, 1981 r explicitly created, used, released by apps r client/server paradigm r two types of.
UNIT-6. Basics of Networking TCP/IP Sockets Simple Client Server program Multiple clients Sending file from Server to Client Parallel search server.
Java Programming II Java Network (I) Java Programming II.
1 CSCD 330 Network Programming Fall 2013 Some Material in these slides from J.F Kurose and K.W. Ross All material copyright Lecture 8a Application.
Network Programming: Servers. Agenda l Steps for creating a server Create a ServerSocket object Create a Socket object from ServerSocket Create an input.
Java How to Program, 9/e © Copyright by Pearson Education, Inc. All Rights Reserved.
Data Communications and Computer Networks Chapter 2 CS 3830 Lecture 11 Omar Meqdadi Department of Computer Science and Software Engineering University.
Network Programming. These days almost all devices.
Liang, Introduction to Java Programming, Ninth Edition, (c) 2013 Pearson Education, Inc. All rights reserved. 1 Chapter 33 Networking.
Network Programming Communication between processes Many approaches:
Clients and Servers 19-Nov-18.
Chapter 2: outline 2.1 principles of network applications
Basic Protocols 24-Nov-18.
Socket programming - Java
Clients and Servers 1-Dec-18.
CSCD 330 Network Programming
Socket Programming.
CSCD 330 Network Programming
Basic Protocols 19-Feb-19.
Socket Programming 2: Application Layer.
Chapter 2: Application layer
Socket Programming with UDP
Review Communication via paired sockets, one local and one remote
Presentation transcript:

Cli/Serv.: jnet/111 Client/Server Distributed Systems v Objectives –describe basic networking in Java – Web page retrieval and sockets programming , Semester 1, Java Networking

Cli/Serv.: jnet/112 Contents 1.Networking Restrictions in Java 2.Basic Networking Classes 3.Sockets (Java Style) 4.Retrieving a Web Page –4 different approaches 5.A Stream Socket Client/Server continued

Cli/Serv.: jnet/113 6.A Datagram Socket Client/Server 7.Networked Tic-Tac-Toe 8.More Information

Cli/Serv.: jnet/ Networking Restrictions in Java v Many browsers place networking restrictions on applets –usually communication is limited to being between your machine and the one where the applet came from  There are no restrictions on Java applications or when using appletviewer

Cli/Serv.: jnet/115 Relaxing Security v Applets can be signed with trusted certificates –a browser can be configured to relax security depending on an applet’s signature –an advanced topic

Cli/Serv.: jnet/ Basic Networking Classes  The J2SE documentation for java.net lists over 30 classes. A few of the key ones:  InetAddress –the class that represents IP addresses and contains operations for manipulating them u see section 2.1 continued

Cli/Serv.: jnet/117  URL –used to retrieve the Web page at the given URL  URLConnection –also used to retrieve a Web page –allows extra parameters to be sent to the URL u e.g HTTP request headers continued

Cli/Serv.: jnet/118  Socket –the client-side socket class for TCP  ServerSocket –the server-side socket class for TCP  DatagramSocket –allows a client or server to send/receive UDP packets

Cli/Serv.: jnet/ Finding an IP Address  Java’s InetAddress class makes the mapping between hostnames and IP addresses much easier than in UNIX.  For details, look at the the documentation for java.net.InetAddress

Cli/Serv.: jnet/1110 WhatIP.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); } }

Cli/Serv.: jnet/1111 Use Carried out from a DOS prompt on my Windows machine.

Cli/Serv.: jnet/ Sockets (Java Style) v 1. Stream Sockets –the client/server connection exists for the entire duration of the request and answer u similar to a telephone call –a connection-oriented service u corresponds to TCP –Java has separate classes for client and server stream sockets (see section 5)

Cli/Serv.: jnet/1113 v 2. Datagram Sockets –the client/server send messages (packets, datagrams) to each other u similar to the postal service –a connectionless service u corresponds to UDP –Java has classes for datagram sockets and packets (see section 6).

Cli/Serv.: jnet/ Pinging  ping uses the ICMP protocol's ECHO_REQUEST datagram. The host’s answer is an ICMP ECHO_RESPONSE. ping is a DOS command, not Java.

Cli/Serv.: jnet/1115  ICMP packets can only be created via a socket of type SOCK_RAW. –but Java only supports SOCK_STREAM (TCP) and SOCK_DGRAM (UDP) sockets  Our solution: use a TCP connection to the daytime service to pretend to ping –the daytime server listens at port 13

Cli/Serv.: jnet/ DayPing.java JJ2, 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 "); System.exit(0); } :

Cli/Serv.: jnet/1117 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

Cli/Serv.: jnet/1118  DayPing.java converts the socket connection into a BufferedReader –this allows readLine() to be used for socket input v Using layered streams to add I/O functionality on top of sockets is a powerful feature of Java. Notes

Cli/Serv.: jnet/1119 Use v v C> javac DayPing.java v v C> java DayPing calvin calvin is alive at Sat May 7 13:46: v v C> java DayPing fourdots Exception 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

Cli/Serv.: jnet/1120 v v C> java DayPing takasilla Exception in thread "main" java.net.UnknownHostException: takasilla at java.net.PlainSocketImpl. connect(Unknown Source) : at ping.main(DayPing.java:23) v v C> java DayPing Exception 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

Cli/Serv.: jnet/ Why Doesn't DayPing Work? v The examples that don't work show three different errors: –ConnectException –UnknownHostException –NoRouteToHostException v The "unknown host" exception is caused by an incorrect IP address. continued

Cli/Serv.: jnet/1122 v The "connection" exception probably means that the server is unavailable (switched off) –this can be confirmed for a TCP service by trying to connect to it with telnet : $ telnet fourdots 13 Trying telnet: Unable to connect to remote host: Connection refused $ continued executed from a different machine (fivedots)

Cli/Serv.: jnet/1123 v The "no route to host" exception usually means that there is a firewall preventing the connection from being made.  telnet response: $ telnet 13 Trying telnet: Unable to connect to remote host: Connection timed out $ A long wait, and then... tried on (fivedots)

Cli/Serv.: jnet/ Firewalls at PSU takasila calvin fivedots Departmental firewall (no external socket creation; URLs allowed) ratree Univ. firewall (no external socket creation; URLs only through the ‘cache’ proxy) cache The Internet University CoE Department (simplified) 8080

Cli/Serv.: jnet/1125 v Ordinary users (i.e. students) cannot write socket-based programs that communicate outside PSU –this is true in any language (Java, C, etc.)  But programs can retrieve Web pages (and other things) using the Java URL class –the URL request must go through PSU's cache machine

Cli/Serv.: jnet/1126 URLs and Sockets v From your data communications course, you may recall that the Web protocol, HTTP, is built on top of TCP/IP. v Java's URL class uses stream sockets (TCP/IP) for its implementation –so why does it get past cache ? continued

Cli/Serv.: jnet/1127  cache accepts socket links to valid Web servers, but also checks that the HTTP GET (or POST) message includes additional valid HTTP headers. –all of this HTTP stuff is carried out by the URL class for us

Cli/Serv.: jnet/ Retrieving a Web Page v Five ways of obtaining a Web page: –1. use a socket, and send a GET message to the server  see GetSocketPage.java –2. use a URL object, and read the page via a stream  see GetURLPage.java continued

Cli/Serv.: jnet/1129 –3. use a URL object, and display the page in a browser  see showPage.java –4. display a URL in an JEditorPane  see ShowURLPage.java –5. use a HTTP URL connection, and send a GET message u see Java’s networking tutorial

Cli/Serv.: jnet/ Sockets and GET  GetSocketPage.java retrieves the page: /index.html e.g.  It prints the text of the page to stdout. continued

Cli/Serv.: jnet/1131 v It opens a socket at port 80 for the host, which is the usually place where the Web server is listening.  It sends the HTTP GET message: GET /index.html

Cli/Serv.: jnet/1132 Diagram GetSocketPage client host Web server GET /index.html Web page (as text) 80

Cli/Serv.: jnet/1133 GetSocketPage.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); :

Cli/Serv.: jnet/1134 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

Cli/Serv.: jnet/1135  GetSocketPage.java converts the socket connection into a BufferedReader for input, and a PrintStream for output –uses readLine() for socket input –uses println() for socket output Notes

Cli/Serv.: jnet/1136 Use C> javac GetSocketPage.java C> java GetSocketPage fivedots Un title page : C> text of Web page printed to stdout

Cli/Serv.: jnet/1137 But... Exception in thread "main" java.net.ConnectException: Connection timed out: connect at java.net.PlainSocketImpl. socketConnect(Native Method) : at GetSocketPage.main(GetSocketPage.java:18) C> java GetSocketPage Exception in thread "main" java.net.ConnectException: Connection timed out: connect at java.net.PlainSocketImpl. socketConnect(Native Method) : at GetSocketPage.main(GetSocketPage.java:18) The firewall around PSU prevents Web server access by sockets. continued

Cli/Serv.: jnet/1138 v cache rejected the GET message to the external site since the message didn't include additional HTTP headers. v These can be supplied by us, but it's easier to use the URL class.

Cli/Serv.: jnet/ URL Object  GetURLPage.java avoids the firewall problem with sockets by using a URL object.  A URL object allows a Web page to be retrieved as a stream of text –our program prints the text to stdout.

Cli/Serv.: jnet/1140 GetURLPage.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() )); :

Cli/Serv.: jnet/1141 String line; while ( (line = dis.readLine()) != null ) System.out.println(line); dis.close(); } catch (Exception e) { System.out.println(e); } } } // end of GetURLPage.java

Cli/Serv.: jnet/1142  A stream for the URL object is obtained using openStream() –after that the same input stream layering technique is used as in GetSocketPage.java –there is no need to send a GET message Notes

Cli/Serv.: jnet/1143 Use v v C> javac GetURLPage.java v v C> java GetURLPage java.net.ConnectException: Connection timed out: connect v v C> java -DproxySet=true -DproxyHost=cache.psu.ac.th -DproxyPort=8080 GetURLPage Amazon Page : C> typed on one line after a long wait

Cli/Serv.: jnet/1144  Ordinary users can access outside PSU by using URLs, but they must route their requests via PSU cache machine.

Cli/Serv.: jnet/1145 Batch Files for Long Commands  GetURLPage.bat off echo Executing GetURLPage... java -DproxySet=true -DproxyHost=cache.psu.ac.th -DproxyPort=8080 GetURLPage %1 v Use: c> GetURLPage : // same output as last slide

Cli/Serv.: jnet/1146 Proxy Username/Password v A further level of firewall security is to require the user to enter a username and password –called proxy authorization v Java has network support for authorization –it allows a username and password to be sent by a client program to the firewall continued

Cli/Serv.: jnet/1147 v A good tutorial: –“Jump a Proxy/Firewall and Live to Tell About it” javapro/2000/03mar00/te0003/te0003.asp  Slightly modified code is in GetThroughProxy.java at: Software.coe/Cliserv/ Code%20Examples/Java%20Code/ Basic%20Networking/

Cli/Serv.: jnet/ Passing a URL to a Browser v If the Java code is in an applet, then the downloaded URL can be displayed in the browser.  showPage.html displays a user-specified Web page in the (Opera) browser, using the ShowPage.java applet.

Cli/Serv.: jnet/1149 Usage continued The dialog box appears in front of the browser window.

Cli/Serv.: jnet/1150 Loaded Page:

Cli/Serv.: jnet/1151 showPage.html Web Page Loading Applet Web Page Loading Applet Applet is placed here... Web Page Loading Applet Web Page Loading Applet Applet is placed here...

Cli/Serv.: jnet/1152 showPage.java import java.net.*; import javax.swing.*; import java.applet.AppletContext; import javax.swing.JOptionPane; public class ShowPage extends JApplet { public void init() { try { String urlString = JOptionPane.showInputDialog( "Enter a URL:"); URL url = new URL(urlString); :

Cli/Serv.: jnet/1153 AppletContext browser = getAppletContext(); browser.showDocument(url); } catch (Exception e) { System.out.println(e); } } // end of init() } // end of ShowPage AppletContext browser = getAppletContext(); browser.showDocument(url); } catch (Exception e) { System.out.println(e); } } // end of init() } // end of ShowPage

Cli/Serv.: jnet/1154 Notes  The download only works because the browser is set up to work through cache. v There are no Java security restrictions on a applet passing a URL to a browser to be displayed. continued

Cli/Serv.: jnet/1155  A URL is downloaded with showDocument(), which must be called in the applet’s environment (i.e. the browser): –AppletContext browser = getAppletContext(); browser.showDocument(url);  The URL is automatically loaded into the browser, replacing showPage.html. continued

Cli/Serv.: jnet/1156  There is a two-argument version of showDocument() that can load URLs into frames.  D&D contains a more complex example ( SiteSelector.java, ch. 21) which allows the user to select a URL from a list.

Cli/Serv.: jnet/ Displaying a URL with JEditorPane  The Swing GUI includes JEditorPane which allows 'structured' text to be displayed and edited. –offers basic support for plain text, RTF, and HTML –see javax.swing.JEditorPane continued

Cli/Serv.: jnet/1158  A JEditorPane can be filled by calling setPage() with a URL string argument.  JEditorPane also has support for capturing hyperlink clicks as events. continued

Cli/Serv.: jnet/1159 v With these features, it is possible to write a basic Web browser!  ShowURLPage.java has a text field for the user to enter a URL –the resulting downloaded page is displayed in a JEditorPane –if a link is clicked inside the pane, then its page will be loaded automatically continued

Cli/Serv.: jnet/1160 I clicked on “School of Advanced...”

Cli/Serv.: jnet/1161 ShowURLPage’s Event Model enter contents X hyperlinkUpdate() {...} GUI Code actionPerformed() {...} hyperlink events action events ^ ^

Cli/Serv.: jnet/1162 ShowURLPage.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; :

Cli/Serv.: jnet/1163 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); :

Cli/Serv.: jnet/1164 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()); } }); :

Cli/Serv.: jnet/1165 c.add( new JScrollPane(contents), BorderLayout.CENTER); setDefaultCloseOperation( JFrame.EXIT_ON_CLOSE); setSize(400, 300); setVisible(true); } // end of ShowURLPage()

Cli/Serv.: jnet/1166 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()

Cli/Serv.: jnet/1167 public static void main(String args[]) { new ShowURLPage(); } } // end of ShowURLPage class

Cli/Serv.: jnet/1168 Use C> javac ShowURLPage.java C> java ShowURLPage // A request for // 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.

Cli/Serv.: jnet/1169 Notes  The JEditorPane must be set uneditable so that hyperlinks events can be captured.  Hyperlink events include: ENTERED, EXITED, and ACTIVATED. –see javax.swing.event.HyperlinkEvent continued

Cli/Serv.: jnet/1170  getPage() calls setPage() to display a URL in the JEditorPane –the call is surrounded by changes to the cursor icon so things look busy  getPage() is called in two possible ways: –as a response to pressing enter in the textfield –as a response to a link being clicked

Cli/Serv.: jnet/ A Stream Socket Client/Server AlienClient.java AlienServer1.java socketServer socket socket for client comms the new socket is made with accept() Initial Internet connection input and output streams input and output streams

Cli/Serv.: jnet/1172 v The server creates a new socket when a client contacts it –client/server communication via the new socket –this frees up the main server socket to receive connections from other clients –AlienServer1.java is an iterative server u it can only process one client at a time continued

Cli/Serv.: jnet/1173  Our client and server both run on localhost.  AlienServer1 actions: –wait for a client connection –after a connection, wait for a message from the client –respond depending on the content of the message –close the client connection, and loop, waiting for another client continued

Cli/Serv.: jnet/1174 Diagram for Client Processing AlienClient.java AlienServer1.java 1. send message 4. send answer 2. analyse message 3. print message locally 5. close socket

Cli/Serv.: jnet/1175 AlienServer1.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); :

Cli/Serv.: jnet/1176 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() ) ); :

Cli/Serv.: jnet/1177 // 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

Cli/Serv.: jnet/1178 The client: AlienClient.java  AlienClient.java ’s actions: –open a connection with the server –send a message taken from the command line –receive and print the server’s response –close

Cli/Serv.: jnet/1179 AlienClient.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() ); :

Cli/Serv.: jnet/1180 // 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

Cli/Serv.: jnet/1181 Use Client: Server: I used two separate DOS windows on the same machine.

Cli/Serv.: jnet/1182 Telnet Client (from fivedots) Server: I typed this

Cli/Serv.: jnet/1183 A More Complex Example v D&D gives a larger stream socket client/server example (ch. 21): –object input and output streams are used –the sequence of communication is more complex u the client maintains a long-lived link with the server until it sends a “TERMINATE” string

Cli/Serv.: jnet/ A Concurrent Server  AlienServer2.java uses threads to handle multiple clients concurrently. v Three main advantages: –the server code is simpler since server processing is in a separate class called Worker –clients do not have to wait –the server is more scaleable

Cli/Serv.: jnet/1185 AlienServer2 Visually AlienServer2 AlienClient clients4444 Worker threads each Worker thread can deal with multiple messages from its client

Cli/Serv.: jnet/ Java Threads (Briefly) v There are two ways to create a thread: –extend the Thread class –write a class to implement the Runnable interface  We use the first approach since Worker does not need to extend any other classes. continued

Cli/Serv.: jnet/1187  A class extended from Thread must define the run() method: class Worker extends Thread { public void run() {... } } class Worker extends Thread { public void run() {... } }  A threaded object is started by calling start() : Worker w = new Worker(...): w.start(); Worker w = new Worker(...): w.start();  The thread will call run() itself from within start().

Cli/Serv.: jnet/ 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; } :

Cli/Serv.: jnet/1189 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() )); :

Cli/Serv.: jnet/1190 // 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.

Cli/Serv.: jnet/1191 // 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

Cli/Serv.: jnet/1192 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

Cli/Serv.: jnet/1193 Use Server:

Cli/Serv.: jnet/1194 Client on fivedots

Cli/Serv.: jnet/1195 Two Local Clients (one closed)

Cli/Serv.: jnet/ A Datagram Socket Client/Server UDPClientUDPServer Datagram socket 5000 Datagram socket any port msg packets echo

Cli/Serv.: jnet/ Server Event Model display X GUI Code ^ ^ packet 2) echo back to client waitForPackets() {...} packet 1) receive from client

Cli/Serv.: jnet/ 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; :

Cli/Serv.: jnet/1199 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()

Cli/Serv.: jnet/11100 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); :

Cli/Serv.: jnet/11101 // 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())); :

Cli/Serv.: jnet/11102 // 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() ); } :

Cli/Serv.: jnet/11103 catch(IOException io) { display.append(io.toString() + "\n"); io.printStackTrace(); } } } // end of waitForPackets{} public static void main( String args[] ) { new UDPServer(); } } // end of UDPServer

Cli/Serv.: jnet/11104 Server Notes v The server creates one datagram socket at port 5000: socket = new DatagramSocket(5000); v Datagram socket creation must be inside a try/catch block. continued

Cli/Serv.: jnet/11105  The server loops inside waitForPackets() –creates an empty packet (100 bytes long) –blocks inside receive()  When receive() returns, the packet contains data and: –the Internet address of the sender –the port number of the sender –the actual length of the data continued

Cli/Serv.: jnet/11106 v The packet information can be accessed via methods. e.g.: receivePacket.getPort(); receivePacket.getData();  receive() must be in a try/catch block. continued

Cli/Serv.: jnet/11107 v The server echoes the datagram back to the client at the address and port obtained from the client’s message: sendPacket = new DatagramPacket( receivePacket.getData(), receivePacket.getLength(), receivePacket.getAddress(), receivePacket.getPort() ); socket.send(sendPacket); sendPacket = new DatagramPacket( receivePacket.getData(), receivePacket.getLength(), receivePacket.getAddress(), receivePacket.getPort() ); socket.send(sendPacket);  send() must be in a try/catch block.

Cli/Serv.: jnet/ Client Event Model enter display X GUI Code actionPerformed() {...} action events ^ ^ packet 1) send to server waitForPackets() {...} packet 2) receive echo from sender

Cli/Serv.: jnet/ 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; :

Cli/Serv.: jnet/11110 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); :

Cli/Serv.: jnet/11111 try { socket = new DatagramSocket(); } catch(SocketException se) { se.printStackTrace(); System.exit(1); } waitForPackets(); } // end of UDPClient()

Cli/Serv.: jnet/11112 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); :

Cli/Serv.: jnet/11113 // 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()

Cli/Serv.: jnet/11114 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); :

Cli/Serv.: jnet/11115 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

Cli/Serv.: jnet/11116 Client Notes  The client gets the data for each packet from the user entering a string into a TextField.  The client creates a datagram socket with no specified port number: socket = new DatagramSocket(); continued

Cli/Serv.: jnet/11117  In actionPerformed(), the user’s input is converted into a packet, and sent to the server: sendPacket = new DatagramPacket( data, data.length(), InetAddress.getLocalHost(), 5000); socket.send(sendPacket); v The code assumes that the server is on the same machine as the client, and attached to port continued

Cli/Serv.: jnet/11118  The client receives the echoed reply in waitForPackets() : –the loop blocks inside receive() until a packet arrives from the server –the packet details are displayed in the JTextArea  The blocked waitForPackets() does not stop the user from entering more strings for the client to send out –the GUI always runs in a separate thread

Cli/Serv.: jnet/ Use continued 1. message sent to server 3. Echoed message received from the server 2. Client message received and echoed Tested by starting the client and server in two separate DOS windows.

Cli/Serv.: jnet/11120 Another message sent and echoed back:

Cli/Serv.: jnet/ Networked Tic-Tac-Toe D&D Section 21.8, p.1031 thread 5000 synchronized validMove() thread Client: Player ‘X’ Server data thread Client: Player ‘O’ data

Cli/Serv.: jnet/11122 Output p

Cli/Serv.: jnet/ More Information v Chapter 21, Deitel & Deitel (D&D) Books.html#Network  Killer Game Programming in Java Chapter 29, Network Basics  Killer Game Programming in Java Chapter 29, Network Basics

Cli/Serv.: jnet/11124 v Core Java 2, Vol II - Advanced Features Cay S. Horstmann & Gary Cornell Sun Microsystems Press, 2001, chapter 3 –multithreaded server, sending , URLConnection, HTTP POST – Books.html#Network

Cli/Serv.: jnet/11125 v Aj. Somchai's Java Site –Network and Distributed Programming Books Books.html#Network