250 likes | 378 Views
Fall 2005 Socket Programming. Qutaibah Malluhi Computer Science and Engineering Qatar University. TCP/IP Stack. In this chapter. Application. TCP. IP. Introduction. Internet protocols (TCP/IP) provide General-purpose facility for reliable data transfer Mechanism for contacting hosts
E N D
Fall 2005Socket Programming Qutaibah Malluhi Computer Science and Engineering Qatar University
TCP/IP Stack In this chapter Application TCP IP
Introduction • Internet protocols (TCP/IP) provide • General-purpose facility for reliable data transfer • Mechanism for contacting hosts • Application programs • Use internet protocols to contact other applications • Provide user-level services • Application-level protocols provide high-level services • DNS • Electronic mail • Remote login • FTP • World Wide Web • All of these applications use client-server architecture
Client-Server Paradigm • Server application is "listener" • Waits for incoming message • Performs service • Returns results • Examples: • Web server • FTP server • Client application establishes connection • Sends message to server • Waits for return message • Examples: • Web Browser • FTP client tools • FTP command line interface, etc.
Transport Protocols • Clients and servers exchange messages through transport protocols; e.g., TCP or UDP • Both client and server must have same protocol stack and both interact with transport layer • Can have multiple Servers on the same machine
Identifying Sessions • How do incoming messages get delivered to the correct server? • Unique address to identify the machine (IP address) • TCP or UDP protocol port numbers can be used to identifier multiple servers on same machine. • Servers listens to a predetermined port • Each transport session has two unique identifiers • (IP address, port number) on server • (IP address, port number) on client • No two clients on one computer can use same source port • Client end-end points (client IP Address, port number) are unique sessions are unique
Network Servers • Servers continuously running on machines waiting (listening) for connection requests. • Servers usually listen for a particular port on the machine they are running on. • Ports enable us run many servers on the same machine • Sample server ports (): • day time 13 • FTP 21 • SMTP 25 • who is 43 • login 513 • http 80 • Check /etc/services file on Unix and netstat –an on Windows • Check http://www.iana.org/assignments/port-numbers for more info • Can have your own servers running on a port other than already used ports -- avoid standard ports numbers < 1024
“Netstat” output C:\>netstat –anActive ConnectionsProto Local Address Foreign Address StateTCP 0.0.0.0:135 0.0.0.0:0 LISTENINGTCP 0.0.0.0:427 0.0.0.0:0 LISTENINGTCP 0.0.0.0:445 0.0.0.0:0 LISTENINGTCP 0.0.0.0:1035 0.0.0.0:0 LISTENINGTCP 127.0.0.1:1025 0.0.0.0:0 LISTENINGTCP 143.132.91.165:139 0.0.0.0:0 LISTENINGUDP 0.0.0.0:427 *:*UDP 0.0.0.0:445 *:*UDP 0.0.0.0:500 *:*UDP 0.0.0.0:1026 *:*UDP 0.0.0.0:1036 *:*UDP 0.0.0.0:1063 *:*UDP 0.0.0.0:2812 *:*UDP 0.0.0.0:4500 *:*UDP 0.0.0.0:38037 *:*UDP 127.0.0.1:123 *:*UDP 127.0.0.1:1900 *:*UDP 127.0.0.1:3200 *:*UDP 143.132.91.165:123 *:*UDP 143.132.91.165:137 *:*UDP 143.132.91.165:138 *:*UDP 143.132.91.165:1900 *:* C:\>
Telnet to Debug Servers • telnet host port-number • Try this: • Get time of day on stallion: • telnet www.time.gov 13 • telnet nist1.datum.com 13 (66.243.43.21) • Get QU home page • telnet www.qu.edu.qa 80 • get <Enter> <Enter> • Send an Email using an SMTP server • telnet mail.qu.edu.qa 25 • follow sendmail protocol
Protocol Example (SMTP) >>>Telnet mail.yahoo.com 25 220 ESMTP mail.yahoo.com Sendmail 980427.SGI.8.8.8/950213.SGI.AUTOCF ready at Wed, 31 Jan 2001 17:49:30 -0600 (CST) >>>HELO qmpc 250 mail.yahoo.com Hello [143.132.91.85], pleased to meet you >>>MAIL FROM: qmalluhi@jsums.edu 250 qmalluhi@jsums.edu... Sender ok >>>RCPT TO: user@yahoo.com 250 user@yahoo.com... Recipient ok >>DATA 354 Enter mail, end with "." on a line by itself This is my email message You got it. SMTP is simple . 250 RAA06347 Message accepted for delivery >>>Quit
Socket Connections • Import java.net package • Many things can go wrong over the network -- Use try/Catch block • Open a socket Socket s = new Socket(”www.time.gov", 13); • Get input stream on the socket InputStream in = s.getInputStream(); • Once you have grabbed the stream, you can read from it • Close() closes the socket Host Name or IP address Port number
Steps for Reading and Writing to Sockets • Open a socket. • Open an input stream and output stream to the socket. • Read from and write to the stream according to the server's protocol. • Close the streams. • Close the socket. Only step 3 differs from client to client, depending on the server. The other steps remain largely the same
Example: Socket Connection 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); 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); } } catch (IOException e) { System.out.println("Error" + e); } } }
Network Servers • Every server program (http, smtp, ftp, etc.) continues to execute the following loop: • wait listening to a socket • get command from client through an incoming data stream associated with that socket • fetch and process information • send information back to client through an outgoing data stream Output stream Input steam request Client Server Input steam Output stream reply
Creating Java server (1) • The server program begins by creating a new ServerSocket object to listen on a specific port try { serverSocket = new ServerSocket(8587); } catch (IOException e) { . . . } • Using the accept method, server waits (blocks indefinitely) listening for a client connection requests on the port of this server – accept returns a socket object Socket clientSocket = null; try { clientSocket = serverSocket.accept(); } catch (IOException e) {. . .}
Creating Java Server (2) • Server communicates with the client: • Gets the socket's input and output stream and opens readers and writers on them. • Get I/O objects for communication • OutputStream - sends info to client • InputStream - gets info from client • Server's input stream is client's output stream, and vice versa • Use Socket object to get references to streams • clientSocket.getInputStream() • clientSocket.getOutputStream() • May construct the proper I/O stream, reader, or writer depending on the Client-Server protocol – See later slides • Server communicates with the client by reading from and writing to the socket using the captured streams. • Methods write(),read(), readLine(), print(),etc.
Creating Java Server (3) • Housekeeping by closing all of the input and output streams, client socket, and server socket: out.close(); in.close(); clientSocket.close(); serverSocket.close(); • Notice that networking appears as sequential file I/O • Sockets simplify networking
Example: Echo Server 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())); 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); if (line.trim().equals("BYE")) done = true; } } incoming.close(); } catch (Exception e) { System.out.println(e); } } }
Threaded Servers • For handling multiple clients – use a thread for handling each client. while (true) { accept a connection ; create a thread to deal with the client ; } //end while
Example: Threaded Echo Server (1) 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++; } } catch (Exception e) { System.out.println(e); } } }
Example: Threaded Echo Server (2) class ThreadedEchoHandler extends Thread { public ThreadedEchoHandler(Socket i, int c) { incoming = i; counter = c; } 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; 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(); } catch (Exception e) { System.out.println(e); } } private Socket incoming; private int counter; }
For transmitting text readLine() of BufferedReader print()andprintln() of PrintWriter Binary data DataInputStream DataOutputStream Using Stream I/O Classes BufferedReader in = new BufferedReader (new InputStreamReader(socket.getInputStream())); PrintWriter out = new PrintWriter (socket.getOutputStream(), true /* autoFlush */); DataInputStream in = (new DataInputStream(socket.getInputStream())); DataOutputStream out = (new DataOutputStream(socket.getOutputStream()));
Creating Java Client • Create Socket to connect to server Socket connection = new Socket(serverAddress, port) • If successful, returns Socket. May throw a subclass of IOException • Get stream objects • connection.getInputStream() • connection.getOutputStream() • Use captured streams to create proper stream types for Client-Server protocol • Processing phase -- Communicate using stream objects • Termination • Transmission complete • connection.close() (close Socket) • Client must determine when server done • readblocks until input data is available, the end of the stream is detected, or an exception is thrown – May throw a subclass of IOException • read returns -1 when eof found • For some InputStreams read May generates EOFException
Internet Addresses • Internetworked machines have names (www.jsums.edu) and IP addresses (143.132.91.21) • Host may have multiple IP addresses • Can use InetAddress class to convert between the two. • static InetAddress getByName(String host) • static InetAddress[] getAllByName(String host) • static InetAddress getLocalHost() • String getHostAddress()Returns the IP address string "%d.%d.%d.%d”. • String getHostName()Gets the host name for local machine. For more details check API
Email Client send(null); send("HELO " + hostName); send("MAIL FROM: " + "qmalluhi@qu.edu.qa"); send("RCPT TO: " + "user@yahoo.com"); send("DATA"); out.println("This is a test email"); send("."); s.close(); } catch (IOException exception) { System.out.println("Error: " + exception); } } } public void send(String s) throws IOException { if (s != null) { out.println(s); out.flush(); } String line; if ((line = in.readLine()) != null) System.out.println("I Recieved: "+line +"\n"); } } import java.net.*; import java.io.*; public class MailTest { PrintWriter out; BufferedReader in; public static void main(String[] args ) { MailTest T = new MailTest(); T.sendEMail(); } public void sendEMail() { try { Socket s = new Socket("143.132.1.13", 25); out = new PrintWriter(s.getOutputStream()); in = new BufferedReader(new InputStreamReader(s.getInputStream())); String hostName = InetAddress.getLocalHost().getHostName();