Survey
* Your assessment is very important for improving the workof artificial intelligence, which forms the content of this project
* Your assessment is very important for improving the workof artificial intelligence, which forms the content of this project
Learning Outcomes • • • • Networking To understand basic network terminology To be able to communicate using Telnet To be aware of some common network services To be able to implement client and server programs in Java using the following classes: – Sockets – Server sockets – URL connections 1 CP4044 – Lecture 7 2 CP4044 – Lecture 7 TCP/IP Networks Sockets • Common, basic communications mechanism. Clients – A bi-directional serial communication channel that associates two network connected computers. – Acts like a pipe that allows data flow (via a stream) between the computers. Network Server • As far as the programmer is concerned: – Data is written to a socket in exactly the same way as it would be written to a file or display. – It can then be read from the other end of the socket in exactly the same way as data is read from a file or keyboard. • TCP/IP networks are based on a packetswitched, client/server model • A server runs continuously, listening for requests from clients • A client initiates a transaction with the server • The intricacies of communications are handled within the socket class. – As a Java programmer you can get by without knowing much about networking. 3 CP4044 – Lecture 7 TCP/IP Hostnames and DNS • IP (Internet Protocol) routes data to the destination machine • Each machine connected to the network has a unique IP address, e.g. 134.220.1.9 • TCP (Transmission Control Protocol) looks after the transmission of data. – Provides a reliable, connection-oriented transport – Delivers the data to a process identified by a port number • A socket encapsulates – the IP address of the destination machine – the Port number of a process running on that machine CP4044 – Lecture 7 Kevan Buckley, Peter Burden, CP4044, 2004 4 CP4044 – Lecture 7 • The host name is the name of the server machine. – In a form that is easily remembered/used by humans – e.g. www.scit.wlv.ac.uk • The IP protocol actually needs an Internet address. – e.g. 134.220.1.9 • Host names are translated into IP addresses by DNS, the Domain Name System. • Why have two ways of referring to the same host? – Allows the host to be moved to a different machine – only DNS entries need to be changed – users unaffected – Humans don't like using strings of numbers – Computers like numbers – allows easy implementation of hierarchies, subnets etc. 5 CP4044 – Lecture 7 6 1 Ports Some Well-Known Port Numbers • Ports allow machines to provide multiple services. • A server process listens on a specific (published) port for requests. Port Name RFC Purpose 13 Daytime 867 Gets the date and time 21 FTP 959 Transfers files 23 Telnet 854 Log on to a remote system • Ports are identified by a 16-bit integer. 25 SMTP 821 Internet mail service 70 Gopher 1436 Document archives 80 http 1945 Transfers Web resources 110 Pop3 1939 Download Internet mail – Ports up to 1024 are reserved for specific services – Ports above 1025-32767 are free for use. • Used by clients, they are known as ephemeral ports and are allocated numbers starting at 32767 working down. RFCs are obtained from http://www.faqs.org/rfcs/ 7 CP4044 – Lecture 7 8 CP4044 – Lecture 7 Server Client • A client process attempts to create a socket connection to a remote server, usually in response to some sort of user initialised event. • A server process runs in a loop, continually listening for connection requests via its server socket. • Once a connection request has been received the server process can then read data from the socket and process it. • It then resumes listening for the next request. • A common model is for the server process to create a new process to service the request, so that it can immediately resume listening for the next connection request. • Client/server communication is similar to a telephone conversation: – Somebody (the client) picks up a phone and dials a number. – Another phone rings and somebody (the server) picks it up. – A bi-directional conversation then continues until somebody hangs up. – The phone number called is similar to an IP address. – Ports are similar to different extension numbers. 9 CP4044 – Lecture 7 Telnet World Wide Web Service • The Telnet command line tool uses the Telnet protocol (http://www.faqs.org/rfcs/rfc854.html), based on TCP/IP, to allow a computer to act as a remote terminal on another machine anywhere on the Internet. • It allows us to experiment with client/server systems. command prompt server 10 CP4044 – Lecture 7 port C:\> telnet clun.scit.wlv.ac.uk 80 CP4044 – Lecture 7 Kevan Buckley, Peter Burden, CP4044, 2004 11 • HTTP – Port 80 – http://www.faqs.org/rfcs/rfc2616.html – Web servers listen on port 80 for connections – Once connected the client can send a number of simple commands. e.g. GET followed by the name of a resource. – We can retrieve raw HTML using a Telnet client C:\> telnet www.scit.wlv.ac.uk 80 Trying 134.220.4.130... Connected to clun.scit.wlv.ac.uk. Escape character is '^]'. GET <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.or g/TR/html4/loose.dtd"> <html lang="en"> <head> <meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1"> <title>School of Computing and IT</title> 12 CP4044 – Lecture 7 2 File Transfer Protocol Service Network Programming with Java • FTP – Port 21 • Java provides many classes for programming in a TCP/IP network environment • These are in the java.net package • Writing client/server programs which implement sockets, use these classes: – http ://www.faqs.org/rfcs/rfc959.html – FTP servers listen on port 21 for connections – USER and PASS commands are required before other commands can be issued. C:\> telnet ftp.scit.wlv.ac.uk 21 Trying 134.220.4.130... Connected to clun.scit.wlv.ac.uk. Escape character is '^]'. 220 clun FTP server (Version 4.143 Mon Oct 16 15:20:07 BST 2000) ready. USER anonymous 331 Guest login ok, send e-mail address as password. PASS [email protected] ... Output omitted ... QUIT 230- Goodbye Connection to host lost – java.net.ServerSocket – java.net.Socket • A number of higher-level classes are available. We look at just one: – java.net.URL 13 CP4044 – Lecture 7 14 CP4044 – Lecture 7 ServerSocket Class Socket Class • import java.net.*; • Constructor: • Constructor: – Socket (String host, int port) – ServerSocket(int port) • Some methods: • Methods include: – InputStream getInputStream() – Socket accept() – OutputStream getOutputStream() – void close() – void setSoTimeout(int timeout) Use this class only for Server programs. – void close() As with all I/O, sockets can throw a variety of exceptions. 15 CP4044 – Lecture 7 01 import java.io.*; 02 import java.net.*; 03 04 public class Server { 05 public static void main(String[] args) { 06 String messageIn, messageOut; 07 try { 08 ServerSocket ssock = new ServerSocket(6789); 09 while (true) { 10 Socket connsock = ssock.accept(); 11 BufferedReader inNet = 12 new BufferedReader( new InputStreamReader( 13 connsock.getInputStream() )); 14 15 DataOutputStream outNet = 16 new DataOutputStream(connsock.getOutputStream()); 17 18 messageIn = inNet.readLine(); 19 messageOut = messageIn.toUpperCase() + "\n"; 20 outNet.writeBytes(messageOut); 21 } 22 }}catch(IOException e) { e.getMessage() }} A Simple Server CP4044 – Lecture 7 Kevan Buckley, Peter Burden, CP4044, 2004 17 16 CP4044 – Lecture 7 Simple Server • Line 7 – The main method may throw exceptions. It requires an exception handler. • Line 8 – Constructs a ServerSocket object to listen on port 6789. • Lines 9-21 – Infinite loop to continually process requests. • Line 10 – Waits (by blocking the thread) for a connection to be made to the ServerSocket. Once connected, the connsock socket can be used to communicate with the client. CP4044 – Lecture 7 18 3 Simple Server • Lines 11-14 – Constructs a BuffererReader to read text data line-by-line from the client • Lines 15-16 – Constructs an OutputDataStream to send data to the client. • Lines 18-20 – Read a line of text from the client, convert it to upper case and send it back to the client. 19 CP4044 – Lecture 7 01 02 03 04 05 06 07 08 09 10 11 12 13 14 15 16 17 18 19 Simple Client • Line 5 – Exceptions may be thrown, so use exception handlers. • Lines 6-7 – Construct a BufferedReader to read lines of text from the keyboard. • Line 15 – A line of text is read in through the socket. • Lines 11-12 – Construct a BufferedReader to read in lines of text through the socket. If binary data was required DataInputStream could have been used (to process primitive data types) or bytes could be read directly from the InputStream. • Line 16 – The text that was read from the socket is printed out. • Line 17 – The socket is closed, making it unavailable and freeing up resources. 21 Testing Client/Server Progs CP4044 – Lecture 7 22 Running Programs across the Network • When program testing, it is convenient to run both the server and the client on the same machine • The local machine can be addressed with this reserved address: – IP address: 127.0.0.1 – Hostname: localhost • Run the Server first in one command prompt • Then run the Client in a second command prompt Kevan Buckley, Peter Burden, CP4044, 2004 • Line 13 – A line of text is read from the keyboard into the message variable. • Line 14 – The text stored in the message variable is output through the socket. • Lines 9-10 – Construct a DataOutputStream to send data through the socket. (Note it is necessary to write raw bytes to the socket). CP4044 – Lecture 7 20 CP4044 – Lecture 7 Simple Client CP4044 – Lecture 7 A Simple Client import java.io.*; import java.net.*; ublic class Client { public static void main(String[] args) { try { BufferedReader kbd = new BufferedReader( new InputStreamReader(System.in)); Socket csock = new Socket("localhost", 6789); DataOutputStream outNet = new DataOutputStream(csock.getOutputStream()); BufferedReader inNet = new BufferedReader( new InputStreamReader(csock.getInputStream())); String message = kbd.readLine(); outNet.writeBytes(message + "\n"); message = inNet.readLine(); System.out.println("Server sent: " + message); csock.close(); }} } • Run the Server and Client programs on separate networked machines • You will need to know the IP address of the machine that the Server is running on: ipconfig (for Windows) ifconfig (for Linux) • Use this IP address when creating the socket in the Client program • Will not be able to connect if the machine is running a firewall 23 CP4044 – Lecture 7 24 4 Universal Resource Locator (URL) The Java URL class • Identifies a resource on the internet • The URL class has a number of uses, including: – Validating a url string entered by the user http://www.wlv.ac.uk:80/~in6659/clientserver/index.html protocol host port path If not specified uses the default for the given protocol, e.g. 80 for http The location of the resource being requested • Will throw MalformedURLException if the string does not have valid syntax – Parsing a url string • Class provides methods to return the different parts of the url string • getProtocol(), getHost(), getPath(), getPort(), etc. – Provides high level means of communication URLs may contain other information such as user names, passwords and locations of resources within resources. • Do not need to create sockets • openStream() See http://www.faqs.org/rfcs/rfc1738.html 25 CP4044 – Lecture 7 Using the URL Class 01 import java.io.*; 02 import java.net.*; 26 CP4044 – Lecture 7 URL Class Example The URL class allows simplified communication for common protocols. • Line 7 – The main method may throw exceptions. 03 public class GetURL { 04 05 06 07 public static void main(String[] args) { try { URL url = new URL(args[0]); 08 InputStreamReader inStr = new InputStreamReader(in); 10 BufferedReader inNet = new BufferedReader(inStr); 12 while ((line = inNet.readLine()) != null) { 13 • Lines 13-16 – Continually reads data from the BufferedReader until it fails to read any more (null is received). lineCount++; 14 System.out.println(line); 15 } 16 18 • Lines 9-12 – Opens up an InputStream to read from the URL and attaches it to a BufferedReader to allow line-by-line data retrieval. InputStream in = url.openStream(); 09 17 • Line 8 – Uses the text that was passed as a parameter to this program to construct a URL object. String line; int lineCount = 0; System.out.println("Lines read = " + lineCount); } 27 CP4044 – Lecture 7 28 CP4044 – Lecture 7 Validating and Parsing a URL Summary 01 import java.net.*; • Introduced some TCP/IP services 02 public class DisplayURL { 03 public static void main(String[] args) { 04 URL url = null; 05 try { url = new URL(args[0]); 06 } catch(MalformedURLException e) { 07 System.out.println("Bad url"); 08 – Telnet - remote connection – WWW and FTP services • New Java classes introduced: System.exit(1); 09 } 10 System.out.println(url); 12 System.out.println("Protocol: "+url.getProtocol()); 13 System.out.println("Path: "+url.getPath()); 14 System.out.println("Host: "+url.getHost()); 15 System.out.println("Port: "+url.getPort()); 16 System.out.println("Query: "+url.getQuery()); 17 System.out.println("File: – java.net.ServerSocket – java.net.Socket – java.net.URL "+url.getFile()); 18 } } CP4044 – Lecture 7 Kevan Buckley, Peter Burden, CP4044, 2004 29 CP4044 – Lecture 7 30 5