1 fall 2005 socket programming qutaibah malluhi computer science and engineering qatar university

25
1 Fall 2005 Socket Programming Qutaibah Malluhi Computer Science and Engineering Qatar University

Post on 22-Dec-2015

222 views

Category:

Documents


0 download

TRANSCRIPT

Page 1: 1 Fall 2005 Socket Programming Qutaibah Malluhi Computer Science and Engineering Qatar University

1

Fall 2005

Socket Programming

Qutaibah MalluhiComputer Science and Engineering

Qatar University

Page 2: 1 Fall 2005 Socket Programming Qutaibah Malluhi Computer Science and Engineering Qatar University

2

TCP/IP Stack

ApplicationApplicationIn this chapter

TCP

IP

Page 3: 1 Fall 2005 Socket Programming Qutaibah Malluhi Computer Science and Engineering Qatar University

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

Page 4: 1 Fall 2005 Socket Programming Qutaibah Malluhi Computer Science and Engineering Qatar University

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.

Page 5: 1 Fall 2005 Socket Programming Qutaibah Malluhi Computer Science and Engineering Qatar University

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

Page 6: 1 Fall 2005 Socket Programming Qutaibah Malluhi Computer Science and Engineering Qatar University

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

Page 7: 1 Fall 2005 Socket Programming Qutaibah Malluhi Computer Science and Engineering Qatar University

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

info Can have your own servers running on a port other than

already used ports -- avoid standard ports numbers < 1024

Page 8: 1 Fall 2005 Socket Programming Qutaibah Malluhi Computer Science and Engineering Qatar University

8

“Netstat” outputC:\>netstat –an

Active Connections

Proto 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:\>

Page 9: 1 Fall 2005 Socket Programming Qutaibah Malluhi Computer Science and Engineering Qatar University

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 <Enter> <Enter>

– Send an Email using an SMTP server» telnet mail.qu.edu.qa 25» follow sendmail protocol

Page 10: 1 Fall 2005 Socket Programming Qutaibah Malluhi Computer Science and Engineering Qatar University

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: [email protected]

250 [email protected]... Sender ok

>>>RCPT TO: [email protected]

250 [email protected]... 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

Page 11: 1 Fall 2005 Socket Programming Qutaibah Malluhi Computer Science and Engineering Qatar University

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 socketInputStream 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

Page 12: 1 Fall 2005 Socket Programming Qutaibah Malluhi Computer Science and Engineering Qatar University

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

Page 13: 1 Fall 2005 Socket Programming Qutaibah Malluhi Computer Science and Engineering Qatar University

13

Example: Socket Connectionimport 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); } }}

Page 14: 1 Fall 2005 Socket Programming Qutaibah Malluhi Computer Science and Engineering Qatar University

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

ClientClient ServerServer

request

reply

Input steam

Input steam Output stream

Output stream

Page 15: 1 Fall 2005 Socket Programming Qutaibah Malluhi Computer Science and Engineering Qatar University

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)

Page 16: 1 Fall 2005 Socket Programming Qutaibah Malluhi Computer Science and Engineering Qatar University

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 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 (2)

Page 17: 1 Fall 2005 Socket Programming Qutaibah Malluhi Computer Science and Engineering Qatar University

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)

Page 18: 1 Fall 2005 Socket Programming Qutaibah Malluhi Computer Science and Engineering Qatar University

18

Example: Echo Serverimport 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); } }}

Page 19: 1 Fall 2005 Socket Programming Qutaibah Malluhi Computer Science and Engineering Qatar University

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

Page 20: 1 Fall 2005 Socket Programming Qutaibah Malluhi Computer Science and Engineering Qatar University

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); } }}

Page 21: 1 Fall 2005 Socket Programming Qutaibah Malluhi Computer Science and Engineering Qatar University

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;}

Page 22: 1 Fall 2005 Socket Programming Qutaibah Malluhi Computer Science and Engineering Qatar University

22

Using Stream I/O Classes

For transmitting text– readLine() of BufferedReader

– print()andprintln() 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()));

Page 23: 1 Fall 2005 Socket Programming Qutaibah Malluhi Computer Science and Engineering Qatar University

23

Create Socket to connect to serverSocket 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 InputStreams read May generates EOFException

Creating Java Client

Page 24: 1 Fall 2005 Socket Programming Qutaibah Malluhi Computer Science and Engineering Qatar University

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

Page 25: 1 Fall 2005 Socket Programming Qutaibah Malluhi Computer Science and Engineering Qatar University

25

Email Clientimport 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: " + "[email protected]");

send("RCPT TO: " + "[email protected]");

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"); }

}