Connecting to a Server

Download Report

Transcript Connecting to a Server

CS451
Lecture 4: Network Programming
Yugi Lee
STB #555
(816) 235-5932
[email protected]
www.cstp.umkc.edu/~yugi
*Acknowledgement: This lecture is based on
material courtesy of Monash University
1
CS451 - Lecture 4
Networks
• The communication between processes on
different machines
– logical messages each want to send to each other.
– These messages may be simple strings or arrays of
bytes (binary data).
CS451 - Lecture 4
2
Networks
• At the application programmer level,
– a connection to another process on another machine to
simply send each message as a high level logical unit.
– the underlying layers of software responsible for sending
the message may split it into smaller units for physical
transfer called PDU's (protocol data units).
– With each of these smaller packets will be a wrapper
with additional header information:
 Address of sender/receiver
 Error detection codes
 Protocol control information
CS451 - Lecture 4
3
Protocols
• an agreement between entities (programs) on the
transmission of data.
• exist for different layers of network software.
– At lower levels it allow for determining the amount of data to
be sent, the size of packets and the speed of transmission.
• Connection Control /Data transfer
• Flow control/Error control
• Synchronization/Addressing
– At higher levels (the application level) it may cover the
syntax and sequencing of logical messages.
CS451 - Lecture 4
4
Connection Control
• A program may send information to another at an
indeterminate time with no explicit prior co-ordination
• UDP datagram packets: sent across the network to the
receiving program.
– the packet may get lost or packets may arrive in a different
order to that in which they were sent.
– reorganize the packets and make requests for new packets
when problems occur.
– dynamically routed; split into a number of PDUs that take
different routes to their destination depending on network
congestion.
CS451 - Lecture 4
5
Connection Control
• Alternatively, establish a virtual connection (a link
between two communicating programs)
– Steps: Connection establishment, Data transfer, Connection
termination.
– a connection-oriented protocol such as the TCP/IP (Transfer
Control Protocol / Internet Protocol) used by Sockets
provides sequencing and re-transmission of lost packets.
– send logical messages without having to explicitly deal with
these other issues.
– can be slower as more time is required to set up and
terminate the link.
CS451 - Lecture 4
6
Connection Establishment
• a degree of handshaking where the host accepts
the connection from the client.
• Initial handshaking involves an agreement on
protocols being used:
– the number of unacknowledged packets that can be
send (window size)
– the size of these packets.
CS451 - Lecture 4
7
Connection Establishment
• requires global addresses.
• IP addresses are organized hierarchically:
– 32 bit number to identify the domain, the network,
the sub-net and the host.
– The number is divided into four components each
taking a value between 0 and 255.
– Symbolic names may be associated with the IP
numbers.
– Addresses are determined by using name servers to
look-up the numeric IP address of particular hosts.
CS451 - Lecture 4
8
Connection Establishment
• For example: insect.sd.monash.edu.au




Domain: au Australia
Organisation type: edu Education
Network: monash
Sub-net: sd Department of Software Development
 Machine: insect a Sun sparc station.
CS451 - Lecture 4
9
Connection Establishment
• Internet names are divided into a range of classes to
suit different organizations. Each type of address
allows an additional byte section
– class "C" address provides up to 255 addresses (machines)
for the name holder to use: e.g., 205.161.65.x
– class "B" allows 65,534 addresses: e.g., 128.34.x.x
– class "A" allows for around 16,777,214 addresses: E.g.,
126.x.x.x
• To allow for the growth in the internet the name space
is being expanded to allow for 128 bit numbers rather
than 32 bit number.
CS451 - Lecture 4
10
Connection Establishment
• Once a particular machine has been identified,
the process on the machine the packet is
intended for can be determined by associating
the process with a port.
• A port is a logical abstraction for virtual
connections.
• In TCP/IP a connection is defined as
– the client IP address and port
– the server IP address and port.
CS451 - Lecture 4
11
Issues in Data Transfer
 Sequencing: Packets may arrive out of order and need
to be resequenced by the receiver.
 Flow Control: the sender may try to send more packets
than the receiver can hold in its buffers resulting in
packet loss.
 Error control: as packets are received they are
acknowledged. Missing packets can be re-sent as can
packets which were received but were corrupted in the
network.
CS451 - Lecture 4
12
Issues in Data Transfer
• Synchronization: communicating programs require
information about the state of each other.
– This may require checkpointing and raises similar
issues in relation to the use of monitors and
synchronization of objects.
– Processes simultaneously updating a database may
need to know whether another process has
completed.
– A failure in synchronization in these cases could
lead to dead-lock (the two generals problem).
CS451 - Lecture 4
13
Connection Termination
• Once transmission is complete, typically processes will
cleanly terminate a connection.
• If unexpected terminations occur, a connection based
service will try to live up to its guarantees of delivery.
– When one end of connection terminates (the process was killed or
the machine crashed) the other end may still try to send any
outstanding data.
– wait to try and receive any outstanding data
– Buffers may still be open and maintained after a client has
disconnected if it was not done cleanly.
– Explicitly closing the connection on the server end will force the
server to clear the buffers and clean-up the connection.
CS451 - Lecture 4
14
Socket Programming
• A socket can be described as "one end of a twoway communication between a server program
and a client".
• None of many current programming languages
have socket connectivity built into the language
at such a basic level.
• Java: Socket and ServerSocket classes,
(client and server programs with a minimum of
time and effort).
CS451 - Lecture 4
15
Network Programming
• A key concept in the network programming
– the notion of a port, which is an address uniquely
assigned to a server program, through which the server
can receive connections from client programs.
– From the programmers' point of view, a port is merely a
number uniquely identifying the communication channel
to which the server is listening.
– A client can connect to a particular port by using
programs such as telnet, as follows:
telnet firefly.sd.monash.edu.au 11000
CS451 - Lecture 4
16
Connecting to a Server
• Using the java.net classes makes connecting
to a server incredibly simple
• To enable communication between your Java
client and the server program, by creating
– InputStream (using the getInputStream
method)
– OutputStream from a Socket object (using the
getOutputStream method).
CS451 - Lecture 4
17
Process of Connecting to a Server
1. Identify the host machine on which the server is running
2. Identify the port on the host machine to which the server is
listening
3. Understand the protocol used when communicating with
the server, and code your program to conform to this
protocol:
 If information can be sent to the server, an OutputStream object must
be associated with the Socket
 If information is received from the server (which invariably is the case),
an InputStream object must be associated with the Socket
 All of the demonstration Socket code appearing in this document
adhere to this methodology.
CS451 - Lecture 4
18
Protocol for communicating with the Time
Server
1. Connect to the server on port 13 using telnet or an
equivalent (like the QueryTimeServer Applet)
2. Upon connection, the time server displays the time on
the host machine, then terminates the connection
immediately
 As only one-way communication is needed in this example,
only an InputStream object is associated with the
Socket
 When the input returned from the InputStream is
determined to be null, the server has terminated the
connection
CS451 - Lecture 4
19
Protocol for communicating with the
Finger Server
1. Connect to the server on port 79 using telnet or an
equivalent (like the FingerClient Applet)
2. Upon connection the user has the option to enter the name
of a user on that host machine or just press the ENTER key.
3. Information pertaining to the user entered is returned by the
server, then the server terminates the connection
 As two-way communication needs to be supported by this
example, both OutputStream and InputStream objects
are associated with the Socket
 When the input returned from the InputStream is
determined to be null, the server has terminated the
connection
CS451 - Lecture 4
20
Building a Socket Server
• a server program generally runs continuously whilst it's
host machine is running (usually executed during the
startup procedures of the host machine)
• As with constructing client programs, building any
(socket) server program follows the sequence of steps:
1. Decide on a currently unused port to which your server
will listen (your local sysadmin will know which ports
are free for this purpose)
2. Create a ServerSocket object associated with the
port identified in the previous step
CS451 - Lecture 4
21
Building a Socket Server
3. Create a Socket object from the return value of the
accept method, which blocks (i.e., waits) until a client
has connected to the server
4. Decide on a send-and-receive protocol to which any client
programs must conform if they wish to communicate with
your server
5. Once the protocol has been settled upon, the server knows
– when to send output to the client,
– when to wait for the client's input, and
– what input is deemed valid (or invalid) and the correct
response to valid (or invalid) input
CS451 - Lecture 4
22
Building a Socket Server
6. The Socket object can then be used to open
InputStream and OutputStream objects from
which to receive and send data to the server
• The easiest way to test a server program for
correct functionality is to use telnet
– to connect to the correct host machine and port for
your server, and, conforming to the communication
protocol assumed by the server,
– to test that the server responds in an appropriate
manner to your sample input.
CS451 - Lecture 4
23
Datagram Communication
• The rules governing the use of datagrams are rather
more restrictive than those associated with sockets (less
frequently used than sockets)
• Client/Server Communication
– Socket communication: the existence of a "perfect channel",
which is permanently open and guarantees the arrival of
information at the destination in the same order in which it
departed from the source.
– Datagram communication: when such conditions are not
required of the communication (i.e., where a constant channel
is not needed and where the sequence of the data is
irrelevant)
CS451 - Lecture 4
24
Datagram Communication
• Packets (the data to be communicated) contains the address
of the intended recipient, and the port to which the recipient
is bound.
• It is routed from the client to the server using a nondeterministic path which could change for successive
packets,
• It gives no guarantee of packets arriving in the original
sending sequence.
• For a limited set of communication domains like single
send and/or receive transfers, datagram communication is
appropriate.
CS451 - Lecture 4
25
Datagram Communication
java.net package:
• DatagramSocket: the link through which the client and
server communicate, and objects of this class need to be
created by both programs. If no port is specified when
creating an object of this type, the port is allocated
dynamically.
• DatagramPacket: acts as a container for a byte array
containing the information to be transferred, the address of
the receiver, and port to which the receiver is connected.
CS451 - Lecture 4
26
Creating a Datagram Server
• Steps:
– The server attaches (binds) itself to a particular port,
– then creates a packet initially either to send or receive data,
depending on the communication protocol.
• As with most servers, the body of the serving
mechanism is encased in an infinite loop.
• the example server has not been threaded to allow
multiple concurrent accesses, but the technique to do so
is the same as with socket-based servers.
CS451 - Lecture 4
27
Creating a Datagram Server
import java.io.*;
import java.net.*;
import java.util.*;
public class QuoteServer {
private static Vector quotes
= new Vector();
private DatagramSocket socket
= null;
public static void
main(String args[]) {
setupQuotes();
new QuoteServer();
}
QuoteServer() {
try {
socket = new
DatagramSocket(12000);
System.out.println
("QuoteServer listening on
port: "+
socket.getLocalPort());
} catch
(java.net.SocketException
e)
{System.err.println("Could
not create datagram
socket.");
}
CS451 - Lecture 4
28
Creating a Datagram Server
while (true) {
try {
byte[] packetBuffer = new
byte[256];
String quoteString = null;
// receive request
DatagramPacket packet = new
DatagramPacket(packetBuffer,
256);
socket.receive(packet);
InetAddress clientAddress =
packet.getAddress();
int clientPort =
packet.getPort();
quoteString = getAQuote();
packetBuffer =
quoteString.getBytes();
29
packet = new
DatagramPacket(packetBuffer,
packetBuffer.length,
clientAddress,
clientPort);
socket.send(packet);
} catch (IOException e) {
System.err.println("IOException
: " + e);
}}}
protected void finalize() {
if (socket != null) {
socket.close();
socket = null;
System.out.println("Closing
datagram socket.");
}
CS451
} - Lecture 4
Creating a Datagram Server
private static void setupQuotes() {
quotes.addElement("Life wasn't meant to be easy");
quotes.addElement("The recession we had to have");
quotes.addElement("I have a huge whiteboard in my office");
quotes.addElement("Please explain?");
quotes.addElement("The things that batter");
quotes.addElement("No child shall live in poverty");
quotes.addElement("Porcus Madonna");
quotes.addElement("Don't you worry about that");}
private static String getAQuote() {
return (String) quotes.elementAt
((int)(Math.random() * (float) quotes.size()));
}
}
CS451 - Lecture 4
30
Creating a Datagram Server
 The server begins by creating a DatagramSocket object.
 getLocalPort: if no port was specified it could ask the socket for
the port
 The server creates a DatagramPacket by constructors
 for sending data, the constructor needs a data buffer
containing the information to send, the length of the
data buffer, and the address and port of the recipient
 for receiving data, the constructor needs a data buffer to
store the information being received, and the length of
the buffer.
CS451 - Lecture 4
31
Creating a Datagram Server
 receive(java.net.DatagramPacket): blocks
until a client connects to the server
 getAddress(): The address of a client
connecting to a server can be obtained by
querying a received packet for it's
address(InetAddress)
 getPort(): The port of a client connecting
to a server can be obtained by querying a
received packet for it's port
 send: Once a DatagramPacket has been
created for sending, it is routed to the
address and port specified in the packet
CS451 - Lecture 4
32
Creating a Datagram Client
public class QuoteClientFrame
extends Frame implements
ActionListener {
Button b = new
Button("Get Quote");
b.addActionListener(this)
public void
actionPerformed(ActionEvent
event) {
int port = 0;
InetAddress hostAddress =
null;
DatagramSocket socket =
null;
DatagramPacket packet =
null;
byte[] sendBuffer = new
byte[PACKET_SIZE];
try {
// bind to the socket
socket = new
DatagramSocket();
} catch
(java.net.SocketException e)
{
System.err.println("Could
not create datagram
socket.");
}
CS451 - Lecture 4
33
Creating a Datagram Client
if (socket != null) {
try {
// send request
port Integer.parseInt
(serverPort.getText().trim();
hostAddress =
InetAddress.getByName(serve
rName.getText());
packet = new
DatagramPacket(sendBuffer,
PACKET_SIZE,
hostAddress,
port);
socket.send(packet);
// get response
packet = new
DatagramPacket(sendBuffer,
PACKET_SIZE);
socket.receive(packet);
String received = new
String(packet.getData());
currentQuote.setText(received);
socket.close();
} catch (IOException e) {
System.err.println("IOException
: " + e);
}}}}
CS451 - Lecture 4
34
Creating a Datagram Client
• Like a server, a datagram client also binds to a
DatagramSocket object through which communication
occurs
 All client programs need knowledge of the machine on
which the server is running; the machine name is
turned into a InetAddress object using the getByName
method
 If the specified size of the data in a receiving packet is
less than the actual size of the data in the packet
received, the data is truncated to the size specified
CS451 - Lecture 4
35
When to use Datagrams?
• They can be used for short messages which are not
critical if not received (the client can request the
data again).
• Also useful for live Video or Audio feeds, in these
cases a few lost packets may not be critical.
• For other purposes where you may need high speed
communication and survive without the overhead
of flow control and guaranteed ordered delivery.
CS451 - Lecture 4
36