Anda di halaman 1dari 14

ICS 432

LAB MANUAL
COMPUTER NETWORK SYSTEMS

Department of Information and Computer Science College of Computer Science and Engineering King Fahd University of Petroleum and Minerals 2005

ICS 432 LAB

Socket Programming

ICS 432

LAB 7
SOCKET PROGRAMMING

1. Objectives:

To learn the basics of Socket programming To learn the difference between TCP sockets and UDP datagrams To build a daytime C/S To build a SMTP mail user agent using JAVA To build a simple web server using JAVA

2. Background Information:
2.1. Socket-Definition: A socket is one endpoint of a two-way communication link between two programs running on the network. A socket is bound to a port number so that the TCP layer can identify the application that data is destined to be sent. 2.2. TCP/IP and UDP/IP communications: There are two communication protocols that one can use for socket programming: datagram communication and stream communication. 2.3. Datagram communication: The datagram communication protocol, known as UDP (user datagram protocol), is a connectionless protocol, meaning that each time you send datagrams, you also need to send the local socket descriptor and the receiving socket's address. As you can tell, additional data must be sent each time a communication is made. 2.4. Stream communication: The stream communication protocol is known as TCP (transfer control protocol). Unlike UDP, TCP is a connection-oriented protocol. In order to do communication over the TCP protocol, a connection must first be established between the pair of sockets. While one of the sockets listens for a connection request (server), the other asks for a connection (client). Once two sockets have been connected, they can be used to transmit data in both (or either one of the) directions. The selection of protocol [UDP or TCP] depends on the client/server application you are writing. The following discussion shows the differences between the UDP and TCP protocols; this might help you decide which protocol you should use. In UDP, as you have read above, every time you send a datagram, you have to
ICS 432 LAB Socket Programming 2

ICS 432

send the local descriptor and the socket address of the receiving socket along with it. Since TCP is a connection-oriented protocol, on the other hand, a connection must be established before communications between the pair of sockets start. So there is a connection setup time in TCP. In UDP, there is a size limit of 64 kilobytes on datagrams you can send to a specified location, while in TCP there is no limit. Once a connection is established, the pair of sockets behaves like streams: All available data are read immediately in the same order in which they are received. UDP is an unreliable protocol and so there is no guarantee that the datagrams you have sent will be received in the same order by the receiving socket. On the other hand, TCP is a reliable protocol; it is guaranteed that the packets you send will be received in the order in which they were sent. In short, TCP is useful for implementing network services such as remote login (rlogin, telnet) and file transfer (FTP) which require data of indefinite length to be transferred. UDP is less complex and incurs fewer overheads. It is often used in implementing client/server applications in distributed systems built over local area networks.

3. Sockets using UDP connection:


3.1. Creating a datagram socket.

If you are programming a client, then you would open a socket like this:
//Creating a socket DatagramSocket socket=new DatagramSocket(); //create a buffer of size 256 byte[] sendbuf = new byte[256]; byte[] receivebuf = new byte[256]; //create an inet address of the server machine InetAddress address = InetAddress.getByName("196.1.65.205"); //create the message String message="Hello Datagram server"; sendbuf=message.getBytes(); //construct the packet DatagramPacket packet = new DatagramPacket(sendbuf, sendbuf.length, address, 4445);
ICS 432 LAB Socket Programming 3

ICS 432

//send the packet socket.send(packet); // get response packet = new DatagramPacket(receivebuf, receivebuf.length); socket.receive(packet);

If you are programming a server, then you would open a socket like this:
//Create a socket DatagramSocket socket= new DatagramSocket(4445); byte[] sendbuf = new byte[256]; byte[] receivebuf = new byte[256]; // receive request DatagramPacket packet = new DatagramPacket(receivebuf, receivebuf.length); socket.receive(packet); String received = new String(packet.getData()); System.out.println(received); // get the address of the client machine InetAddress address = packet.getAddress(); // get the port of the client machine int port = packet.getPort(); dString = "Hello User from "+address; sendbuf = dString.getBytes(); // construct the packet packet = new DatagramPacket(sendbuf, sendbuf.length, address, port); //send the message
ICS 432 LAB Socket Programming 4

ICS 432

socket.send(packet);

4. Sockets using TCP connection:


4.1. Opening a socket.

If you are programming a client, then you would open a socket like this:
Socket MyClient; try { MyClient = new Socket("Machine name", PortNumber); }catch (IOException e) { System.out.println(e); }

Where Machine name is the machine you are trying to open a connection to, and PortNumber is the port (a number) on which the server you are trying to connect to is running. When selecting a port number, you should note that port numbers between 0 and 1,023 are reserved for standard protocols, such as SMTP, FTP, and HTTP. When selecting a port number for your server, select one that is greater than 1023. If you are programming a server, then this is how you open a socket:
ServerSocket MyService; try { MyServerice = new ServerSocket(PortNumber); } catch (IOException e) { System.out.println(e); }

When implementing a server you also need to create a socket object from the ServerSocket in order to listen for and accept connections from clients.
ICS 432 LAB Socket Programming 5

ICS 432

Socket clientSocket = null; try { serviceSocket = MyService.accept(); }catch (IOException e) { System.out.println(e);} 4.2. Creating an input stream.

On the client side, you can use the BufferedReader class to create an input stream to receive response from the server:
BufferedReader in = new BufferedReader(new InputStreamReader(socket.getInputStream())); On the server side, you can use DataInputStream to receive input from the client: BufferedReader in = new BufferedReader(new InputStreamReader(socket.getInputStream())); 4.3. Creating an output stream.

On the client side, you can create an output stream to send information to the server socket using the class PrintWriter.
PrintWriter out = new PrintWriter(socket.getOutputStream(), true); On the server side, you can use the class PrintStream to send information to the client. PrintWriter out = new PrintWriter(socket.getOutputStream(), true); 4.4. Closing sockets.

You should always close the output and input stream before you close the socket.

ICS 432 LAB

Socket Programming

ICS 432

On the client side:


try { in.close(); out.close(); socket.close(); } catch (IOException e) { System.out.println(e); }

On the server side:


try { in.close(); out.close(); socket.close(); serverSocket.close(); } catch (IOException e) { System.out.println(e); }

5. Examples:
5.1. Handshaking of the client and the server: Download the following files. HelloClient.java HelloServer.java Execute HelloServer.java first, then execute HelloClient.java and follow the prompt. 5.2. Echo Client and Server Programs: Download the files EchoClient.java and EchoServer1.java and study the implementation of the socket, execute and see the output. 5.3. Server handling more than one client: Download the files EchoServer.java and EchoServerThread.java and study the implementations of the socket. Now try to understand the difference in implementation of sockets in these programs and those of Example 2.

5.4. A simple Web server:


Download the Web server program in java given to you which serve web pages to the browser and study the implementation using sockets.

6. Exercises:
6.1. Daytime C/S program: Write a server program which sends the time of day information to the client. Note: To get the date and time in the server, you can use import java.util.*;
ICS 432 LAB Socket Programming 7

ICS 432

Calendar c=new GregorianCalendar(); Date t=c.getTime(); 6.2. Writing an SMTP and POP3 Client Program: The working of email system is shown in the following figure. The email from the source is taken to the remote email server using SMTP. From the remote client, you need to use a pull protocol like POP3 or IMAP and get the email from the respective email server.

6.2.1. Setting up the POP3 Server

1. Go

to

Administrative

Tools

and

select

Add

or

Remove

Windows

Components.

ICS 432 LAB

Socket Programming

ICS 432

2. Tick the E-Mail Services option and press details. Press OK and Next to start the installation. Once this is complete, close all open windows.

3. After you have installed the POP3 Service, you are ready to setup and configure mailboxes. Open the main window by pressing Start > Programs > Administrative Tools > POP3 Service.

ICS 432 LAB

Socket Programming

ICS 432

4. Once that is done, the first thing you have to do is create a domain. Do this by right clicking the server name in the main window, select new > domain. Type the name of your desired domain and click OK.

5. Further to this, you are now able to create a mailbox by right clicking the domain, pressing New > Mailbox. Type the mailbox name and the password in the appropriate boxes and press OK.

6. A confirmation box should pop up notifying you that the mailbox was successfully added. Select the "Do not show this message again" if you do not wish to have this box appear everytime you add a mailbox.

ICS 432 LAB

Socket Programming

10

ICS 432

7. The new mailbox you created is shown in the main window. As you can see in the following window, the "State" of the mailbox is "Unlocked" and therefore available for use. If you right click the mailbox and select "Lock", you will disable it.

6.2.2. SMTP Procedure In order to work with SMTP server, you need to follow the following procedure: 1. Initially, you need to connect to the server via port number 25.

a. This can be done using telnet servername 25. Where servername


is the IP address of your SMTP server. 2. Issue the HELO command as HELO domainname 3. We have to indicate from whom the email originates MAIL FROM: <emailid@domainname> Remember to use your email address along with the domain name.
ICS 432 LAB Socket Programming 11

ICS 432

Also, note that there is no blank space between the colon and the word FROM. 4. We have to indicate to whom the email designates RCPT TO: <emailid@domainname> Remember to use your email address along with the domain name. Also, note that there is no blank space between the colon and the word TO. 5. In order to include the text data you wish to send to the recipient, DATA command as DATA 6. Following the DATA command, you type your email text from the next line. 7. End your email contents by issuing <CRLF>.<CRLF> In programs, you can replace CRLF by \r\n 8. Quit the connection using the command QUIT This SMTP example shows mailer.ccse.kfupm.edu.sa, mailer.ccse.kfupm.edu.sa. S: MAIL FROM:<ahmed@ccse.kfupm.edu.sa> R: 250 OK S: RCPT TO:< ibrahim@ccse.kfupm.edu.sa > R: 250 OK S: RCPT TO:< abdallah@ccse.kfupm.edu.sa > R: 250 OK S: DATA R: 354 Start mail input; end with <CRLF>.<CRLF> S: Blah blah blah... S: ...etc. etc. etc. S: <CRLF>.<CRLF>
ICS 432 LAB Socket Programming 12

mail

sent

by

Ahmed

at

host

to Ibrahim and Abdallah at host again in

ICS 432

R: 250 OK S: QUIT An SMTP server always listens to the port 25. Exercise: Write the SMTP client program that can send emails from one account to another. In order to write the SMTP client, you just need to connect to port number 25 using TCP sockets. Then, you should issue all the commands specified above in order and receive the reply. You can check whether your commands where successful or not by checking the response you received from the server. Note: You can check the receipt of your email using Start Programs Administrative Tools POP3 Service. You can notice that the number of messages indicates the number of emails received. To read these emails, you can use POP3. 6.2.3. Reading the email using POP3 service 1. You can read your email using telnet [POP3 runs on port number 110] as below: telnet servername 110 USER username@domain PASS password LIST RETR list-number QUIT

ICS 432 LAB

Socket Programming

13

ICS 432

2. Write a simple POP3 client that can read the emails in your mailbox and
display them to you. POP3 client program is also done similar to that of the SMTP client by connecting to port number 110 and then issuing the POP3 commands in order. telnet servername 110 USER username@domain PASS password STAT LIST list-number RETR list-number QUIT NOTE: For each command there is a reply from POP3 server. For the RETR command, you need to read in a loop until you receive NULL because the email content might be more than one line. The list-number given is the email sequence numbering as it appears in the POP3 server.

ICS 432 LAB

Socket Programming

14

Anda mungkin juga menyukai