Download presentation
Presentation is loading. Please wait.
1
Lecture 10: Networking using Socket Programming
2
Client-Server Model b 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. b An executing program becomes a client when it sends a request to a server and waits for a response.
3
Socket Interface b Sockets provide low level communication mechanism that allow two processes to communicate on same machine or on different machine. b Funded by ARPA (Advanced Research Projects Agency) in 1980. b Developed at UC Berkeley. b Objective is to transport TCP/IP software to UNIX b Now Socket interface has become de facto standard.
4
Socket b Socket is a generalization of the UNIX file access mechanism that provides an endpoint for communication. b Program request the Operating system to create a socket when one is needed. b The system will return a small integer value that the program uses to reference the newly created socket. b 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).
5
Socket Primitives (General approach) b SOCKET Create a new communication end point b BIND Attach a local address to a socket b LISTEN Announce willingness to accept connections. b ACCEPT Block the caller until a connection attempt arrives b CONNECT Actively attempt to establish a connection b SEND Send some data over the connection b RECEIVE Receive some data from the connection b CLOSE Release the connection
6
Passive/Active Socket b A passive socket is used by a server to wait for an incoming connection. b An active socket is used by a client to initiate a connection.
7
SocketTest.java import java.io.*; import java.net.*; public class SocketTest { public static void main(String[] args) public static void main(String[] args) { try try { Socket s = new Socket("time-A.timefreq.bldrdoc.gov", 13); 13);
8
SocketTest.java (Cont.) BufferedReader in = new BufferedReader (new InputStreamReader(s.getInputStream())); (new InputStreamReader(s.getInputStream())); boolean more = true; boolean more = true; while (more) while (more) { String line = in.readLine(); if (line == null) more = false; if (line == null) more = false; else else System.out.println(line); System.out.println(line); } }
9
Cont. catch (IOException e) { System.out.println("Error" + e); } }}
10
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()); } }
11
Output protocol = http host = java.sun.com filename = /docs/books/tutorial/index.html port = 80 ref = DOWNLOADING
12
Socket timeouts b 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.
13
SocketOpenerTest.java import java.io.*; import java.net.*; public class SocketOpenerTest { public static void main(String[] args) { String host; String host; if (args.length > 0) host = args[0]; if (args.length > 0) host = args[0]; else host = "www.yourcompany.com"; else host = "www.yourcompany.com"; int port; int port;
14
SocketOpenerTest.java Cont. if (args.length > 1) port = Integer.parseInt(args[1]); else port = 80; else port = 80; int timeout = 5000; Socket s = SocketOpener.openSocket(host, port, timeout); Socket s = SocketOpener.openSocket(host, port, timeout); if (s == null) System.out.println("The socket could not be opened."); System.out.println("The socket could not be opened."); else else System.out.println(s); System.out.println(s); }}
15
SocketOpenerTest.java Cont. class SocketOpener implements Runnable { public static Socket openSocket(String aHost, int aPort, int timeout) int timeout) { SocketOpener opener = new SocketOpener(aHost, aPort); { SocketOpener opener = new SocketOpener(aHost, aPort); Thread t = new Thread(opener); Thread t = new Thread(opener); t.start(); t.start(); try try { t.join(timeout); { t.join(timeout); }
16
SocketOpenerTest.java Cont. catch (InterruptedException exception) { } return opener.getSocket(); return opener.getSocket(); } public SocketOpener(String aHost, int aPort) { socket = null; { socket = null; host = aHost; host = aHost; port = aPort; }
17
SocketOpenerTest.java Cont. public void run(){ try{ try{ socket = new Socket(host, port); } catch (IOException exception){ catch (IOException exception){ } } public Socket getSocket(){ return socket; } private String host; private String host; private int port; private int port; private Socket socket; private Socket socket;};
18
Internet addresses b High level names are mapped with IP addresses. b You can use InetAddress class if you need to convert between host names and internet addresses. InetAddress address = InetAddress.getByName(“time- A.timefreq.bldrdoc.gov”) ; This method will return 132.163.135.130 b The address 127.0.0.1 is reserved for a local machine and usually used for testing.
19
InetAddressTest.java import java.net.*; public class InetAddressTest { public static void main(String[] args) { try try { if (args.length > 0) if (args.length > 0) { String host = args[0]; { String host = args[0]; InetAddress[] addresses InetAddress[] addresses = InetAddress.getAllByName(host); = InetAddress.getAllByName(host); for (int i = 0; i < addresses.length; i++) for (int i = 0; i < addresses.length; i++) System.out.println(addresses[i]); System.out.println(addresses[i]); }
20
Cont. else { InetAddress localHostAddress { InetAddress localHostAddress = InetAddress.getLocalHost(); = InetAddress.getLocalHost(); System.out.println(localHostAddress); System.out.println(localHostAddress); } } catch (Exception e) catch (Exception e) { System.out.println("Error: " + e); { System.out.println("Error: " + e); } }}
21
TCP/IP b 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.
22
The User Datagram Protocol (UDP) b 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.
23
Layers of Communication Conceptual View
24
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.
25
Inter Process Communication Usage of Ports in Processes communication
26
ServicePort Number ServicePort Number b FTP21 b Telnet23 b SMTP Mail 25 b HTTP (Web) 80 b POP3 Mail 110 b News119
27
Implementing Servers b 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())); (new InputStreamReader(incoming.getInputStream())); PrintWriter out = new PrintWriter PrintWriter out = new PrintWriter (incoming.getOutputStream(), true /* autoFlush */); (incoming.getOutputStream(), true /* autoFlush */);
28
Implementing Servers Cont. b 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.
29
EchoServer.java import java.io.*; import java.net.*; public class EchoServer{ public static void main(String[] args ) {try { ServerSocket s = new ServerSocket(8189); ServerSocket s = new ServerSocket(8189); Socket incoming = s.accept( ); Socket incoming = s.accept( ); BufferedReader in = new BufferedReader BufferedReader in = new BufferedReader (new InputStreamReader(incoming.getInputStream())); (new InputStreamReader(incoming.getInputStream()));
30
EchoServer.java Cont PrintWriter out = new PrintWriter (incoming.getOutputStream(), true /* autoFlush */); (incoming.getOutputStream(), true /* autoFlush */); out.println( "Hello! Enter BYE to exit." ); out.println( "Hello! Enter BYE to exit." ); boolean done = false; while (!done) while (!done) { String line = in.readLine(); { String line = in.readLine(); if (line == null) done = true; if (line == null) done = true; else else { out.println("Echo: " + line); { out.println("Echo: " + line);
31
EchoServer.java Cont if (line.trim().equals("BYE")) done = true; done = true; } } incoming.close(); incoming.close(); } catch (Exception e) catch (Exception e) {System.out.println(e); } }}
32
ThreadedEchoServer.java import java.io.*; import java.net.*; public class ThreadedEchoServer { public static void main(String[] args ) { int i = 1; { int i = 1; try try { ServerSocket s = new ServerSocket(8189); { ServerSocket s = new ServerSocket(8189); for (;;) for (;;) { Socket incoming = s.accept( ); { Socket incoming = s.accept( ); System.out.println("Spawning " + i); System.out.println("Spawning " + i); new ThreadedEchoHandler(incoming, i).start(); new ThreadedEchoHandler(incoming, i).start(); i++; i++; } }
33
ThreadedEchoServer.java Cont catch (Exception e) { System.out.println(e); { System.out.println(e); } }} class ThreadedEchoHandler extends Thread { public ThreadedEchoHandler(Socket i, int c) { incoming = i; counter = c; }
34
ThreadedEchoServer.java Cont public void run() {try { BufferedReader in = new BufferedReader BufferedReader in = new BufferedReader (new InputStreamReader(incoming.getInputStream())); (new InputStreamReader(incoming.getInputStream())); PrintWriter out = new PrintWriter PrintWriter out = new PrintWriter (incoming.getOutputStream(), true /* autoFlush */); (incoming.getOutputStream(), true /* autoFlush */); out.println( "Hello! Enter BYE to exit." ); out.println( "Hello! Enter BYE to exit." ); boolean done = false; boolean done = false;
35
ThreadedEchoServer.java Cont while (!done) { String str = in.readLine(); { String str = in.readLine(); if (str == null) done = true; if (str == null) done = true; else else { out.println("Echo (" + counter + "): " + str); { out.println("Echo (" + counter + "): " + str); if (str.trim().equals("BYE")) done = true; done = true; } } incoming.close(); incoming.close(); }
36
ThreadedEchoServer.java Cont catch (Exception e) { System.out.println(e); { System.out.println(e); } } private Socket incoming; private Socket incoming; private int counter; private int counter;}
37
URLConnectionReader.java import java.net.*; import java.io.*; public class URLConnectionReader { public static void main(String[] args) throws Exception { public static void main(String[] args) throws Exception { URL yahoo = new URL("http://www.yahoo.com/"); URL yahoo = new URL("http://www.yahoo.com/"); URLConnection yc = yahoo.openConnection(); URLConnection yc = yahoo.openConnection(); BufferedReader in = new BufferedReader( BufferedReader in = new BufferedReader( new InputStreamReader( new InputStreamReader( yc.getInputStream())); yc.getInputStream())); String inputLine; String inputLine; while ((inputLine = in.readLine()) != null) while ((inputLine = in.readLine()) != null) System.out.println(inputLine); System.out.println(inputLine); in.close(); in.close(); }}
38
Reverse.java import java.io.*; import java.net.*; public class Reverse { public static void main(String[] args) throws Exception { public static void main(String[] args) throws Exception { if (args.length != 1) { System.err.println("Usage: java Reverse " System.err.println("Usage: java Reverse " + "string_to_reverse"); + "string_to_reverse"); System.exit(1); 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);
39
Reverse.java Cont. PrintWriter out = new PrintWriter( connection.getOutputStream()); 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); System.out.println(inputLine);in.close(); }}
40
An Example of Client-Server application
41
ThreadedDataObjectServer.java import java.io.*; import java.net.*; 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(); }}
42
Server Cont. catch (Exception e) {System.out.println(e);}}} class ThreadedDataObjectHandler extends Thread { public ThreadedDataObjectHandler(Socket i) { incoming = i; }
43
Server Cont. public void run() { try{ ObjectInputStream in = new ObjectInputStream(incoming.getInputStream()); ObjectOutputStream out = new ObjectOutputStream(incoming.getOutputStream()); myObject = (DataObject)in.readObject(); ObjectInputStream in = new ObjectInputStream(incoming.getInputStream()); ObjectOutputStream out = new ObjectOutputStream(incoming.getOutputStream()); myObject = (DataObject)in.readObject(); System.out.println("Message read: " + myObject.getMessage());
44
Server Cont. myObject.setMessage("Got it!"); System.out.println("Message written: " + myObject.getMessage()); out.writeObject(myObject);in.close(); out.close(); out.close();incoming.close();}
45
Server Cont. catch (Exception e) { System.out.println(e); System.out.println(e);}} DataObject myObject = null; private Socket incoming; private Socket incoming;}
46
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; }}
47
Client.java mport java.io.*; import java.net.*; 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()) ; System.out.println("Number : " + myObject.getNumber()); Socket socketToServer = new Socket("127.0.0.1", 3000); ObjectOutputStream myOutputStream = new ObjectOutputStream(socketToServer.getOutputStream()) ;
48
Client ObjectInputStream myInputStream = new ObjectInputStream(socketToServer.getInputStream()); myOutputStream.writeObject(myObject); myObject = (DataObject)myInputStream.readObject(); System.out.println("Number : " + myObject.getNumber()); myOutputStream.close(); myInputStream.close(); myInputStream.close();socketToServer.close(); } catch(Exception e){ System.out.println(e); }}}
49
The End of Lecture 10
Similar presentations
© 2024 SlidePlayer.com. Inc.
All rights reserved.