Download presentation
Presentation is loading. Please wait.
1
1 Fall 2005 Socket Programming Qutaibah Malluhi Computer Science and Engineering Qatar University
2
2 TCP/IP Stack Application In this chapter TCP IP
3
3 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
4
4 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.
5
5 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
6
6 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
7
7 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 infohttp://www.iana.org/assignments/port-numbers Can have your own servers running on a port other than already used ports -- avoid standard ports numbers < 1024
8
8 “Netstat” output C:\>netstat –an Active Connections Proto Local Address Foreign Address State TCP 0.0.0.0:135 0.0.0.0:0 LISTENING TCP 0.0.0.0:427 0.0.0.0:0 LISTENING TCP 0.0.0.0:445 0.0.0.0:0 LISTENING TCP 0.0.0.0:1035 0.0.0.0:0 LISTENING TCP 127.0.0.1:1025 0.0.0.0:0 LISTENING TCP 143.132.91.165:139 0.0.0.0:0 LISTENING UDP 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:\>
9
9 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 –Send an Email using an SMTP server »telnet mail.qu.edu.qa 25 »follow sendmail protocol
10
10 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
11
11 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
12
12 Steps for Reading and Writing to Sockets 1. Open a socket. 2. Open an input stream and output stream to the socket. 3. Read from and write to the stream according to the server's protocol. 4. Close the streams. 5. Close the socket. Only step 3 differs from client to client, depending on the server. The other steps remain largely the same
13
13 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); }
14
14 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 Client Server request reply Input steam Output stream
15
15 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 (1)
16
16 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 u Server's input stream is client's output stream, and vice versa »Use Socket object to get references to streams u clientSocket.getInputStream() u 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 (2)
17
17 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 Creating Java Server (3)
18
18 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); }
19
19 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
20
20 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); }
21
21 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; }
22
22 Using Stream I/O Classes For transmitting text –readLine() of BufferedReader –print() and println() of PrintWriter Binary data –DataInputStream –DataOutputStream 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()));
23
23 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 –read blocks 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 InputStream s read May generates EOFException Creating Java Client
24
24 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
25
25 Email Client 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(); 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"); }
Similar presentations
© 2025 SlidePlayer.com. Inc.
All rights reserved.