Network Programming - RMIT...
Transcript of Network Programming - RMIT...
Network ProgrammingCOSC 1176/1179
Lecture 3
Socket Programming
NetProg 3 2
Port Numbers,
IP & Socket Addresses
The combination of IP address and a port numberis called a socket/endpoint address
NetProg 3 3
Ports and Sockets
• Socket: an API for communication– Raw socket: bypasses the transport layer and uses IP directly
(not covered in this course)
• Port: communication endpoint in a network• Associating a socket with a port is called binding
Socket
Port
Raw socket
NetProg 3 4
Client-Server Sockets and Ports
message
agreed portany port
socketsocket
Internet address = 123.45.67.89Internet address = 123.45.67.88
other ports
client server
Image source: Coulouris, Dollimore, Kindberg: Distributed Systems
NetProg 3 5
Socket Communication
• Lifecycle (Unix model: all data transfers have a similar structure)– Open connection – Read/write data– Close connection
• Servers also need– To advertise their availability (bind to a server port)– Be ready to accept connection requests– Accept a request (and build a connection)
• Characteristics– Communication can be full duplex– Some protocols (e.g. http 1.0) require a full lifecycle (open,
read/write, close) for each request. Others (e.g. http 1.1) allow multiple requests to be processed in one connection.
NetProg 3 6
TCP Client-Server Interaction
Components• Server side
– ServerSocket• Socket for receiving requests from clients to communicate
• A service has only one ServerSocket
• Not used for data exchange
– Communication socket• Socket to exchange data with the client
• There is one communication socket for each client
• Client side– Communication socket
• Socket to exchange data with the server
• The client has only one socket to communicate
NetProg 3 7
Important Socket Classes in Java
• java.net.InetSocketAddress
– Implements an IP socket address (IP address + port number)
• Socket
– Endpoint for communication
• ServerSocket
– Contact point to server
• SocketImpl
– Abstract superclass for all sockets
NetProg 3 8
Socket Address Structure
InetSocketAddress
public InetSocketAddress(InetAddress addr, int port)
InetAddress addr
Means: where in the networkinteger port
Means: where on this computer
Unsigned 16-bit integer (2 full bytes) is actually enoughInet4Address
IPv4 specific
Inet6Address
IPv6 specific
NetProg 3 9
Connection Components in Java
• Socket– Communication endpoint, with transport layer address
– Has to be bound to an (IP address + port number) pairThey identify the host computer and the application process
– The application can bind() the socket to a given port, or the system will pick a port if null is given
• ServerSocket– Class for implementing server sockets– accept() waits for an incoming connection request
– When the ServerSocket accepts a connection request, it creates a socket that can communicate with the client’s socket
• Once the connection has been established, a stream is associated with the connection
NetProg 3 10
The Socket Class
• Creating a socket: s = new Socket()– It comes in several flavours
• If you specify – nothing: you get an unconnected socket
– the remote host (by IP address or host name + remote port number): your socket gets connected
• You can also specify the local IP address + the local port
• Selecting IP addresses and ports– Local IP address: you can select it on a multihomed host
– Local port: you can select it, but it is better to rely on the system choosing a port (ephemeral port)
– Remote address and port: you need to know the connection endpoint
• Methods related to data transfer– connect(SocketAddress endpoint)
Note: you can also specify a timeout
– getInputStream() and getOutputStream() attach a stream to the socket
– shutdownInput() and shutdownOutput()make the corresponding stream unavailable (they do not close the socket)
– close() – disconnects the underlying TCP connection
NetProg 3 11
Socket Code
Client Socket Lifecycle
try {
Socket mySock = new Socket ("saturn.csit.rmit.edu.au", 22);
// Read from / write to the socket}
catch(IOException, except) {
System.err.println(except);
}
finally { // Cleanuptry {
mySock.close();
}
catch(IOException, except)
NetProg 3 12
Socket Code
Stream Usage
InputStream in = socket.getInputStream();
StringBuilder time = new StringBuilder();
InputStreamReader reader = new InputStreamReader(in, "ASCII");// InputStreamReader allows reading characters from a byte stream
for (int c = reader.read(); c != -1; c = reader.read()) {
time.append((char) c);
}
NetProg 3 13
Getting Information about the
Connection • About the local end:
– int getLocalPort()
– InetAddress getLocalAddress()
– SocketAddress getLocalSocketAddress()
• About the remote end– int getPort()
– InetAddress getInetAddress()
– SocketAddress getRemoteSocketAddress()
• You can query the state of the socket– isClosed(), isConnected()
• You can set advanced connection parameters (e.g. traffic class)
NetProg 3 14
Setting Connection Options (1)
Interface SocketOptions
• TCP_NODELAY • Packets are not buffered
• Faster reception of acknowledgements
• May negatively impact on line utilisation
• SO_TIMEOUT • Timeout for blocking operations (in milliseconds)
– If a blocking operation does not complete before the timeout expires, an exception is raised (java.io.InterruptedIOException) but the socket is not closed
• Has to be set before entering the blocking operation
• SO_LINGER • Timeout for sending data after close()
– If all data is sent and acknowledged before it expires, the socket is gracefully closed
– If the sending is not completed before the timeout expires, the socket is closed forcefully with a TCP reset
NetProg 3 15
Setting Connection Options (2)
Interface SocketOptions
• SO_KEEPALIVE • A probe is sent if the connection is idle (no data is exchanged in
either direction) for a predetermined time. The peer has to acknowledge the probe, otherwise the socket is closed.
• Associated methods:setKeepAlive(boolean) getKeepAlive()
• SO_RCVBUF SO_SNDBUF• Gives a hint to the underlying networking software about the TCP
buffer size
– Large buffers: better line utilisation, longer delays
– Small buffers: faster response time, worse line utilisation
• Associated methods:
setReceiveBufferSize(int size)
getReceiveBufferSize(int size)
NetProg 3 16
Socket Exceptions
• Most methods throw IOException or one of its subclass SocketException– Parent class: java.lang.Exception
• SocketException has specific subclasses– BindException, ConnectException,
NoRouteToHostException, PortUnreachableException
• Usagepublic static void bind(ServerSocket socket, InetSocketAddress address, int backlog) throws IOException{
try { socket.bind(address,backlog); }
catch ( BindException e) {
BindException bindException = new BindException("Problembinding to " + address + " : "+ e.getMessage());
bindException.initCause(e);
throw bindException; }
…
}
Code from http://www.programcreek.com/java-api-examples/index.php?api=java.net.SocketException
NetProg 3 17
The ServerSocket Class
• Creating a server socket: s = new ServerSocket()– It has several varieties
• You can specify – nothing: you get an unbound socket– the port on which the server will listen to incoming connection requests – the length of the pending request queue– the local IP address
• IP addresses and ports– Essential information: it tells clients where the server is
– Local IP address: you can select it on a multihomed host
– Local port: you can select it. If you rely on the system for choosing a port (ephemeral port), you will have to retrieve it from the system
• Methods related to the operation– bind(SocketAddress endpoint, int backlog)
If the address is null, the system picks a port number on a valid local address
You can also specify the length of the queue of waiting requests
– accept() listens for connection requests in blocking mode. When one comes, it accepts it
– close() – closes the socket
NetProg 3 18
Server Socket Usage
• Create a server socket ServerSocket server = new ServerSocket(myPort);
• Listen for connectionsSocket connection = server.accept();
• When a connection request arrives, create a communication socket, and attach a stream to it
OutputStream out = connection.getOutputStream();
• Communicate via the socket
Note the type!
NetProg 3 19
Server Socket Lifecycle
ServerSocket server = null;
try {
server = new ServerSocket(port);
// ... work with the server socket} finally {
if (server != null) {
try {
server.close();
} catch (IOException ex) {
// ignore}
}
}
After closing the server socket, it cannot be reconnected
NetProg 3 20
TCP Connections in Java
Communication channel established
Server Program
Client Program
ServerSocket
instance
new
Socket
instance
new
accept()
Blocks until connection
is established
Socket
instance
return from accept()
Creates the socket and connects to
server
NetProg 3 21
TCP Client-Server Interaction
(1)
Client
• 1. Create a TCP socket
• 2. Establish connection
• 3. Communicate
• 4. Close the connection
Server
• 1. Create a TCP (stream) socket
• 2. Bind socket to a port
• 3. Set socket to listen
• 4. Repeatedly:
• a) Accept new connection
• b) Communicate
• c) Close the connection
Server and client perform several steps in a prescribed order toestablish a connection.
NetProg 3 22
TCP Client-Server Interaction
(2)
Client
• 1. Create a TCP socket
• 2. Establish connection
• 3. Communicate
• 4. Close the connection
Server
• 1. Create a TCP (stream) socket
• 2. Bind socket to a port
• 3. Set socket to listen
• 4. Repeatedly:
• a) Accept new connection
• b) Communicate
• c) Close the connection
public ServerSocket(int port, int backlog)
throws IOException
myServerSocket = new ServerSocket(12345, 5);
// Creates a server socket and binds it to the specified
// local port number, with the specified backlog.
NetProg 3 23
TCP Client-Server Interaction
(3)
Client
• 1. Create a TCP socket
• 2. Establish connection
• 3. Communicate
• 4. Close the connection
Server
• 1. Create a TCP (stream) socket
• 2. Bind socket to a port
• 3. Set socket to listen
• 4. Repeatedly:
• a) Accept new connection
• b) Communicate
• c) Close the connection
public Socket accept()
throws IOException
clientSocket = myServerSocket.accept();
// Listens for a connection request to this socket and
// accepts it when it comes. The method blocks until a
// connection is made.
NetProg 3 24
TCP Client-Server Interaction
(4)
Client
• 1. Create a TCP socket
• 2. Establish connection
• 3. Communicate
• 4. Close the connection
Server
• 1. Create a TCP (stream) socket
• 2. Bind socket to a port
• 3. Set socket to listen
• 4. Repeatedly:
• a) Accept new connection
• b) Communicate
• c) Close the connection
Server is now blockedIt is waiting for a connection request from a client
Later, a client decides to talk to the server…
NetProg 3 25
TCP Client-Server Interaction
(5)
Client
• 1. Create a TCP socket
• 2. Establish connection
• 3. Communicate
• 4. Close the connection
Server
• 1. Create a TCP (stream) socket
• 2. Bind socket to a port
• 3. Set socket to listen
• 4. Repeatedly:
• a) Accept new connection
• b) Communicate
• c) Close the connection
public Socket()
// Creates an unconnected socket
mySocket = new Socket();
NetProg 3 26
TCP Client-Server Interaction
(6)
Client
• 1. Create a TCP socket
• 2. Establish connection
• 3. Communicate
• 4. Close the connection
Server
• 1. Create a TCP (stream) socket
• 2. Bind socket to a port
• 3. Set socket to listen
• 4. Repeatedly:
• a) Accept new connection
• b) Communicate
• c) Close the connection
targetAddress = InetSocketAddress("yallara.cs.rmit.edu.au", 12345);
mySocket.connect(targetAddress);
public void connect(SocketAddress endpoint)
public InetSocketAddress(String hostname, int port)
NetProg 3 27
TCP Client-Server Interaction
(7)
Client
• 1. Create a TCP socket
• 2. Establish connection
• 3. Communicate
• 4. Close the connection
Server
• 1. Create a TCP (stream) socket
• 2. Bind socket to a port
• 3. Set socket to listen
• 4. Repeatedly:
• a) Accept new connection
• b) Communicate
• c) Close the connection
Server sees the incoming connection request andreturns from the accept() call
clientSocket = myServerSocket.accept();
// clientSocket now available
NetProg 3 28
TCP Client-Server Interaction
(8)
Client
• 1. Create a TCP socket
• 2. Establish connection
• 3. Communicate
• 4. Close the connection
Server
• 1. Create a TCP (stream) socket
• 2. Bind socket to a port
• 3. Set socket to listen
• 4. Repeatedly:
• a) Accept new connection
• b) Communicate
• c) Close the connection
ByteArrayOutputStream baos;
String message;
baos = clientSocket.getOutputStream();
message = "Hello";
baos.write(message.getBytes(), 0, message.length());
NetProg 3 29
TCP Client-Server Interaction
(9)
Client
• 1. Create a TCP socket
• 2. Establish connection
• 3. Communicate
• 4. Close the connection
Server
• 1. Create a TCP (stream) socket
• 2. Bind socket to a port
• 3. Set socket to listen
• 4. Repeatedly:
• a) Accept new connection
• b) Communicate
• c) Close the connection
ByteArrayInputStream bais;
byte[128] buffer;
bais = mySocket.getInputStream();
bais.read(buffer, 0, 128);
toShow = new String(buffer);
NetProg 3 30
TCP Client-Server Interaction
(10)
Client
• 1. Create a TCP socket
• 2. Establish connection
• 3. Communicate
• 4. Close the connection
Server
• 1. Create a TCP (stream) socket
• 2. Bind socket to a port
• 3. Set socket to listen
• 4. Repeatedly:
• a) Accept new connection
• b) Communicate
• c) Close the connection
// on client side
mySocket.close();
// on server side
clientSocket.close();
Don't close the main server socket! (myServerSocket)
NetProg 3 31
Managing the Connection
• Getting Information about the local end – Information that needs to be advertised to clients
• int getLocalPort()
• InetAddress getInetAddress()
• SocketAddress getLocalSocketAddress()
• You can query the state of the socket• isBound(), isClosed()
• You can set advanced connection parameters• setPerformancePreferences(
int connectionTime,
int latency,
int bandwidth)
You can give the relative importance of these factors (absolute values don’t matter)
• Some socket options (e.g. SO_TIMEOUT) are supported
NetProg 3 32
Example: TCPClient.java
import java.io.*;
import java.net.*;
class TCPClient
{public static void main(String[] args) throws IOException
{String serverHostname = new String ("127.0.0.1");
int serverPort = 10007;
Socket echoSocket = null;
PrintWriter out = null;
BufferedReader in = null;
echoSocket = new Socket(serverHostname, serverPort);
out = new PrintWriter(echoSocket.getOutputStream(), true);
in = new BufferedReader(new InputStreamReader(
echoSocket.getInputStream()));
BufferedReader stdIn = new BufferedReader(new InputStreamReader(System.in));
String userInput;
while ((userInput = stdIn.readLine()) != null)
{out.println(userInput);
System.out.println("echo: " + in.readLine());
}
out.close();
in.close();
stdIn.close();
echoSocket.close();
}
}
NetProg 3 33
Example: TCPServer.javaimport java.io.*;
import java.net.*;
class TCPServer
{public static void main(String[] args) throws IOException
{ServerSocket serverSocket = null;
int serverPort = 10007;
serverSocket = new ServerSocket(serverPort);
Socket clientSocket = null;
clientSocket = serverSocket.accept();
PrintWriter out = new PrintWriter(clientSocket.getOutputStream(), true);
BufferedReader in = new BufferedReader(
new InputStreamReader( clientSocket.getInputStream()));
String inputLine;
while ((inputLine = in.readLine()) != null)
{System.out.println ("Server: " + inputLine);
out.println(inputLine);
if (inputLine.equals("Bye.")) break;
}
out.close();
in.close();
clientSocket.close();
serverSocket.close();
}
}
NetProg 3 34
Client and Server Message
Exchange
• Sockets are used to pass messages
• It is the task of the application to produce the messages
• Next week we will look at the interaction on the message level