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
Lecture 10: Networking using Socket Programming Client-Server Model The term server applies to any program that offers a service that can be reached over a network. A server accepts a request over the network, performs its service, and returns the result to the requester. An executing program becomes a client when it sends a request to a server and waits for a response. Socket Interface Sockets provide low level communication mechanism that allow two processes to communicate on same machine or on different machine. Funded by ARPA (Advanced Research Projects Agency) in 1980. Developed at UC Berkeley. Objective is to transport TCP/IP software to UNIX Now Socket interface has become de facto standard. Socket Socket is a generalization of the UNIX file access mechanism that provides an endpoint for communication. Program request the Operating system to create a socket when one is needed. The system will return a small integer value that the program uses to reference the newly created socket. The application can choose to supply a destination address each time it uses the socket (e.g., when sending datagrams), or it can choose to bind the destination address to the socket and avoid specifying the destination repeatedly (e.g., when making a TCP connection). Socket Primitives (General approach) SOCKET Create a new communication end point BIND Attach a local address to a socket LISTEN Announce willingness to accept connections. ACCEPT Block the caller until a connection attempt arrives CONNECT Actively attempt to establish a connection SEND Send some data over the connection RECEIVE Receive some data from the connection CLOSE Release the connection Passive/Active Socket A passive socket is used by a server to wait for an incoming connection. An active socket is used by a client to initiate a connection. SocketTest.java import java.io.*; import java.net.*; public class SocketTest { public static void main(String[] args) { try { Socket s = new Socket("time-A.timefreq.bldrdoc.gov", 13); SocketTest.java (Cont.) BufferedReader in = new BufferedReader (new InputStreamReader(s.getInputStream())); boolean more = true; while (more) { String line = in.readLine(); if (line == null) more = false; else System.out.println(line); } } Cont. catch (IOException e) { System.out.println("Error" + e); } } } Example import java.net.*; import java.io.*; public class ParseURL { public static void main(String[] args) throws Exception { URL aURL = new URL("http://java.sun.com:80/docs/books/" + "tutorial/index.html#DOWNLOADING"); System.out.println("protocol = " + aURL.getProtocol()); System.out.println("host = " + aURL.getHost()); System.out.println("filename = " + aURL.getFile()); System.out.println("port = " + aURL.getPort()); System.out.println("ref = " + aURL.getRef()); } } Output protocol = http host = java.sun.com filename = /docs/books/tutorial/index.html port = 80 ref = DOWNLOADING Socket timeouts We can set timeout value for a socket object. If we don’t set it then we are on the mercy of underlying operating system. E.g., if we call a read method on a Socket object, it will block our socket until read method will return. SocketOpenerTest.java import java.io.*; import java.net.*; public class SocketOpenerTest { public static void main(String[] args) { String host; if (args.length > 0) host = args[0]; else host = "www.yourcompany.com"; int port; SocketOpenerTest.java Cont. if (args.length > 1) port = Integer.parseInt(args[1]); else port = 80; int timeout = 5000; Socket s = SocketOpener.openSocket(host, port, timeout); if (s == null) System.out.println("The socket could not be opened."); else System.out.println(s); } } SocketOpenerTest.java Cont. class SocketOpener implements Runnable { public static Socket openSocket(String aHost, int aPort, int timeout) { SocketOpener opener = new SocketOpener(aHost, aPort); Thread t = new Thread(opener); t.start(); try { t.join(timeout); } SocketOpenerTest.java Cont. catch (InterruptedException exception) { } return opener.getSocket(); } public SocketOpener(String aHost, int aPort) { socket = null; host = aHost; port = aPort; } SocketOpenerTest.java Cont. public void run(){ try{ socket = new Socket(host, port); } catch (IOException exception){ } } public Socket getSocket(){ return socket; } private String host; private int port; private Socket socket; }; Internet addresses High level names are mapped with IP addresses. You can use InetAddress class if you need to convert between host names and internet addresses. InetAddress address = InetAddress.getByName(“timeA.timefreq.bldrdoc.gov”) ; This method will return 132.163.135.130 The address 127.0.0.1 is reserved for a local machine and usually used for testing. InetAddressTest.java import java.net.*; public class InetAddressTest { public static void main(String[] args) { try { if (args.length > 0) { String host = args[0]; InetAddress[] addresses = InetAddress.getAllByName(host); for (int i = 0; i < addresses.length; i++) System.out.println(addresses[i]); } Cont. else { InetAddress localHostAddress = InetAddress.getLocalHost(); System.out.println(localHostAddress); } } catch (Exception e) { System.out.println("Error: " + e); } } } TCP/IP Transmission Control Protocol standard transport level protocol that provides the reliable, full duplex, stream service on which many application protocols depend. TCP allows a process on one machine to send a stream of data to a process on another. TCP is connection-oriented in the sense that before transmitting data, participants must establish a connection. All data travels in TCP segments, which each travel across the Internet in an Ip datagram. The entire protocol suite is often referred to as TCP/IP because TCP and IP are the two fundamental protocols. The User Datagram Protocol (UDP) The User Datagram Protocol (UDP) provides an unfeliable conncetionless delivery service using IP to transport messages between machines. It uses IP to carry messages, but adds the ability to distinguish among multiple destinations within a fiven host computer. Layers of Communication Conceptual View Usage of Ports Definition: The TCP and UDP protocols use ports to map incoming data to a particular process running on a computer. In datagram-based communication such as UDP, the datagram packet contains the port number of its destination and UDP routes the packet to the appropriate application, as illustrated in this figure: Port numbers range from 0 to 65,535 because ports are represented by 16-bit numbers. The port numbers ranging from 0 - 1023 are restricted; they are reserved for use by well-known services such as HTTP and FTP and other system services. These ports are called well-known ports. Your applications should not attempt to bind to them. Inter Process Communication Usage of Ports in Processes communication Service FTP Telnet SMTP Mail HTTP (Web) POP3 Mail News Port Number 21 23 25 80 110 119 Implementing Servers Server program binds himself on a specific port no. and listen for the client request. Then it sends information on the Net that was requested by client. Following will establish a server that monitors port 8189. ServerSocket s = new ServerSocket (8189) ; Following will tells the program to wait indefinitely until a client connects to that port. After connection it will return a socket object that can be used for I/O. BufferedReader in = new BufferedReader (new InputStreamReader(incoming.getInputStream())); PrintWriter out = new PrintWriter (incoming.getOutputStream(), true /* autoFlush */); Implementing Servers Cont. Every thing that server sends to the server output stream becomes the input of the client program and all the output from the client program ends up in the server input stream. EchoServer.java import java.io.*; import java.net.*; public class EchoServer{ public static void main(String[] args ) { try { ServerSocket s = new ServerSocket(8189); Socket incoming = s.accept( ); BufferedReader in = new BufferedReader (new InputStreamReader(incoming.getInputStream())); EchoServer.java Cont PrintWriter out = new PrintWriter (incoming.getOutputStream(), true /* autoFlush */); out.println( "Hello! Enter BYE to exit." ); boolean done = false; while (!done) { String line = in.readLine(); if (line == null) done = true; else { out.println("Echo: " + line); EchoServer.java Cont if (line.trim().equals("BYE")) done = true; } } incoming.close(); } catch (Exception e) { System.out.println(e); } } } ThreadedEchoServer.java import java.io.*; import java.net.*; public class ThreadedEchoServer { public static void main(String[] args ) { int i = 1; try { ServerSocket s = new ServerSocket(8189); for (;;) { Socket incoming = s.accept( ); System.out.println("Spawning " + i); new ThreadedEchoHandler(incoming, i).start(); i++; } } ThreadedEchoServer.java Cont catch (Exception e) { System.out.println(e); } } } class ThreadedEchoHandler extends Thread { public ThreadedEchoHandler(Socket i, int c) { incoming = i; counter = c; } ThreadedEchoServer.java Cont public void run() { try { BufferedReader in = new BufferedReader (new InputStreamReader(incoming.getInputStream())); PrintWriter out = new PrintWriter (incoming.getOutputStream(), true /* autoFlush */); out.println( "Hello! Enter BYE to exit." ); boolean done = false; ThreadedEchoServer.java Cont while (!done) { String str = in.readLine(); if (str == null) done = true; else { out.println("Echo (" + counter + "): " + str); if (str.trim().equals("BYE")) done = true; } } incoming.close(); } ThreadedEchoServer.java Cont catch (Exception e) { System.out.println(e); } } private Socket incoming; private int counter; } URLConnectionReader.java import java.net.*; import java.io.*; public class URLConnectionReader { public static void main(String[] args) throws Exception { URL yahoo = new URL("http://www.yahoo.com/"); URLConnection yc = yahoo.openConnection(); BufferedReader in = new BufferedReader( new InputStreamReader( yc.getInputStream())); String inputLine; while ((inputLine = in.readLine()) != null) System.out.println(inputLine); in.close(); } } Reverse.java import java.io.*; import java.net.*; public class Reverse { public static void main(String[] args) throws Exception { if (args.length != 1) { System.err.println("Usage: java Reverse " + "string_to_reverse"); System.exit(1); } String stringToReverse = URLEncoder.encode(args[0]); URL url = new URL("http://java.sun.com/cgi-bin/backwards"); URLConnection connection = url.openConnection(); connection.setDoOutput(true); Reverse.java Cont. PrintWriter out = new PrintWriter( connection.getOutputStream()); out.println("string=" + stringToReverse); out.close(); BufferedReader in = new BufferedReader( new InputStreamReader( connection.getInputStream())); String inputLine; while ((inputLine = in.readLine()) != null) System.out.println(inputLine); in.close(); } } An Example of Client-Server application ThreadedDataObjectServer.java import java.io.*; import java.net.*; public class ThreadedDataObjectServer { public static void main(String[] args ) { try { ServerSocket s = new ServerSocket(3000); for (;;) { Socket incoming = s.accept( ); new ThreadedDataObjectHandler(incoming).start(); } } Server Cont. catch (Exception e) { System.out.println(e); } } } class ThreadedDataObjectHandler extends Thread { public ThreadedDataObjectHandler(Socket i) { incoming = i; } Server Cont. public void run() { try { ObjectInputStream in = new ObjectInputStream(incoming.getInputStream()); ObjectOutputStream out = new ObjectOutputStream(incoming.getOutputStream()); myObject = (DataObject)in.readObject(); System.out.println("Message read: " + myObject.getMessage()); Server Cont. myObject.setMessage("Got it!"); System.out.println("Message written: " + myObject.getMessage()); out.writeObject(myObject); in.close(); out.close(); incoming.close(); } Server Cont. catch (Exception e) { System.out.println(e); } } DataObject myObject = null; private Socket incoming; } DataObject.java import java.io.*; import java.util.*; public class DataObject implements Serializable{ private int number; DataObject(){ number = 2; } public int getNumber(){ return number; } public void setNumber(int inNumber){ number = inNumber; } } Client.java mport java.io.*; import java.net.*; public class Client{ public static void main(String[] arg){ try{ DataObject myObject = new DataObject(); myObject.setNumber(1); System.out.println("Number : " + myObject.getNumber()); Socket socketToServer = new Socket("127.0.0.1", 3000); ObjectOutputStream myOutputStream = new ObjectOutputStream(socketToServer.getOutputStream()) ; Client ObjectInputStream myInputStream = new ObjectInputStream(socketToServer.getInputStream()); myOutputStream.writeObject(myObject); myObject = (DataObject)myInputStream.readObject(); System.out.println("Number : " + myObject.getNumber()); myOutputStream.close(); myInputStream.close(); socketToServer.close(); } catch(Exception e){ System.out.println(e); } } } The End of Lecture 10