0% found this document useful (0 votes)
7 views

Lecture 23 Sockets in Java

Uploaded by

Abcd Efgh
Copyright
© © All Rights Reserved
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
7 views

Lecture 23 Sockets in Java

Uploaded by

Abcd Efgh
Copyright
© © All Rights Reserved
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
You are on page 1/ 42

Sockets in Java

UNIT IV
Socket Programming
• What is a socket?
• Using sockets
• Types (Protocols)
• Associated functions
• Styles
What is a socket?
• An interface between application and network
• The application creates a socket
• The socket type dictates the style of communication
• reliable vs. best effort
• connection-oriented vs. connectionless
• Once configured, the application can
• pass data to the socket for network transmission
• receive data from the socket (transmitted through the network by some other
host)
Two essential types of sockets
• STREAM
• a.k.a. TCP Limit on Number of
Processes that can
• reliable delivery successfully request “Listen” for
• in-order guaranteed service at a time service requests

• connection-oriented
Service Request
• bidirectional
2
Service Request
1 Request
Service Request Serviced
Process

3
Connect
Two essential types of sockets
• DATAGRAM
– a.k.a. UDP
– unreliable delivery; data can be
lost, although this is unusual
– no order guarantees
– no notion of “connection” – app Process
indicates dest. for each packet
– can send or receive

Send to recipient

Indeterminate
path
Process

Receive from Sender


Conceptual overview of basic client-
server program
 Write a program that dials up another program at a specified IP address
running on a specified port. Call this program the client.
 Second program (server) accepts connection and establishes
input/output stream to client.
 When server accepts, client can establish input/ouput stream to server
 Client makes request of server by sending data. Server sends replies to
client. Protocol must be defined so client/server understand can interpret
messages.
Ports
• Each host has 65,536
ports Port 0

Port 1
• Some ports are reserved
for specific apps
• 20,21: FTP Port 65535
• 23: Telnet
• 80: HTTP  A socket provides an
interface to send data
to/from the network through
a port
Known Ports
• Some known ports are Client
• 20, 21: FTP Application
• 22: SSH
• 23: TELNET mail client
web browser
• 25: SMTP
• 110: POP3
• 80: HTTP 21 23 25 110 80 119
• 119: NNTP
Objectives
• The InetAddress Class
• Using sockets
• TCP sockets
• Datagram Sockets
Classes in java.net
• The core package java.net contains a number of classes
that allow programmers to carry out network programming
• ContentHandler
• DatagramPacket
• DatagramSocket
• DatagramSocketImplHttpURLConnection
• InetAddress
• MulticastSocket
• ServerSocket
• Socket
• SocketImpl
• URL
• URLConnection
• URLEncoder
• URLStreamHandler
Exceptions in Java
• BindException
• ConnectException
• MalformedURLException
• NoRouteToHostException
• ProtocolException
• SocketException
• UnknownHostException
• UnknownServiceException
The InetAddress Class
• Handles Internet addresses both as host names and as IP
addresses
• Static Method getByName returns the IP address of a
specified host name as an InetAddress object
• Methods for address/name conversion:
public static InetAddress getByName(String host) throws UnknownHostException
public static InetAddress[] getAllByName(String host) throws UnknownHostException
public static InetAddress getLocalHost() throws UnknownHostException

public boolean isMulticastAddress()


public String getHostName()
public byte[] getAddress()
public String getHostAddress()
public int hashCode()
public boolean equals(Object obj)
public String toString()
Find an IP Address: IPFinder.java
// File: IPFinder.java
// Get the IP address of a host

import java.net.*;
import java.io.*;
import javax.swing.*;

public class IPFinder


{
public static void main(String[] args) throws IOException
{ String host;
host = JOptionPane.showInputDialog("Please input the server's name");

try
{InetAddress address = InetAddress.getByName(host);
JOptionPane.showMessageDialog(null,"IP address: " + address.toString());

}
catch (UnknownHostException e)
{JOptionPane.showMessageDialog(null,"Could not find " + host);
}
}
}
Retrieving the current machine’s address

import java.net.*;

public class LocalIP


{
public static void main(String[] args)
{
try
{
InetAddress address = InetAddress.getLocalHost();
System.out.println (address);
}
catch (UnknownHostException e)
{
System.out.println("Could not find local address!");
}
}
}
The Java.net.Socket Class
• Connection is accomplished via construction.
• Each Socket object is associated with exactly one remote host.
• To connect to a different host, you must create a new Socket object.
public Socket(String host, int port) throws UnknownHostException, IOException
• connect to specified host/port
public Socket(InetAddress address, int port) throws IOException
• connect to specied IP address/port
public Socket(String host, int port, InetAddress localAddress, int localPort) throws IOException
• connect to specified host/port and bind to specified local address/port
public Socket(InetAddress address, int port, InetAddress localAddress, int localPort)
throws
IOException
• connect to specified IP address/port and bind to specified local address/port

• Sending and receiving data is accomplished with output and input streams.
There are methods to get an input stream for a socket and an output stream
for the socket.
public InputStream getInputStream() throws IOException
public OutputStream getOutputStream() throws IOException

• To close a socket:
public void close() throws IOException
The Java.net.ServerSocket Class
• The java.net.ServerSocket class represents a server socket. It is
constructed on a particular port. Then it calls accept() to listen
for incoming connections.
• accept() blocks until a connection is detected.
• Then accept() returns a java.net.Socket object that is used to perform
the actual communication with the client.
• the “plug”
• backlog is the maximum size of the queue of connection requests

public ServerSocket(int port) throws IOException


public ServerSocket(int port, int backlog) throws IOException
public ServerSocket(int port, int backlog, InetAddress bindAddr) throws IOException

public Socket accept() throws IOException


public void close() throws IOException
TCP Sockets
Example: SocketThrdServer.java
SERVER:
1. Create a ServerSocket object
ServerSocket servSocket = new ServerSocket(1234);
2. Put the server into a waiting state
Socket link = servSocket.accept();
3. Set up input and output streams
• use thread to serve this client via link
4. Send and receive data
out.println(awaiting data…);
String input = in.readLine();
5. Close the connection
link.close()
Set up input and output streams
• Once a socket has connected you send data to the server via an output
stream. You receive data from the server via an input stream.
• Methods getInputStream and getOutputStream of class Socket:
BufferedReader in =
new BufferedReader(
new InputStreamReader(link.getInputStream()));
PrintWriter out =
new PrintWriter(link.getOutputStream(),true);
TCP Sockets

Example: SocketClient.java
CLIENT:
1. Establish a connection to the server
Socket link =
new Socket(<server>,<port>);
2. Set up input and output streams
3. Send and receive data
4. Close the connection
The UDP classes
• 2 classes:
• java.net.DatagramSocket class
• is a connection to a port that does the sending and receiving. Unlike TCP
sockets, there is no distinction between a UDP socket and a UDP server
socket. Also unlike TCP sockets, a DatagramSocket can send to multiple,
different addresses.The address to which data goes is stored in the packet, not
in the socket.
public DatagramSocket() throws SocketException
public DatagramSocket(int port) throws SocketException
public DatagramSocket(int port, InetAddress laddr) throws SocketException
• java.net.DatagramPacket class
• is a wrapper for an array of bytes from which data will be sent or into which
data will be received. It also contains the address and port to which the packet
will be sent.
public DatagramPacket(byte[] data, int length)
public DatagramPacket(byte[] data, int length, InetAddress host, int port)

• No distinction between server and client sockets


Datagram Sockets
Example: UDPListener.java
SERVER:
1. Create a DatagramSocket object
DatagramSocket dgramSocket =
new DatagramSocket(1234);
2. Create a buffer for incoming datagrams
byte[] buffer = new byte[256];
3. Create a DatagramPacket object for the incoming datagram
DatagramPacket inPacket =
new DatagramPacket(buffer, buffer.length);
4. Accept an incoming datagram
dgramSocket.receive(inPacket)
Datagram Sockets
SERVER:
5. Accept the sender’s address and port from the packet
InetAddress clientAddress = inPacket.getAddress();
int clientPort = inPacket.getPort();
6. Retrieve the data from the buffer
string message =
new String(inPacket.getData(), 0, inPacket.getLength());
7. Create the response datagram
DatagramPacket outPacket =
new DatagramPacket(
response.getBytes(), response.length(),
clientAddress, clientPort);
8. Send the response datagram
dgramSocket.send(outPacket)
9. Close the DatagramSocket: dgram.close();
Datagram Sockets

Example: UDPTalk.java
CLIENT:
1. Create a DatagramSocket object
DatagramSocket dgramSocket = new DatagramSocket;
2. Create the outgoing datagram
DatagramPacket outPacket =
new DatagramPacket(message.getBytes(), message.length(),host,
port);
3. Send the datagram message
dgramSocket.send(outPacket)
4. Create a buffer for incoming datagrams
byte[] buffer = new byte[256];
Datagram Sockets
CLIENT:
5. Create a DatagramPacket object for the incoming datagram
DatagramPacket inPacket =
new DatagramPacket(buffer, buffer.length);
6. Accept an incoming datagram
dgramSocket.receive(inPacket)
7. Retrieve the data from the buffer
string response = new String(inPacket.getData(), 0,
inPacket.getLength());
8. Close the DatagramSocket:
dgram.close();
Handling Data

• Data arrives/is sent as byte array


• To send int
• Convert to string (construct String from it)
• use getBytes() to convert to byte[] and send

• Receive int
• Convert byte[] to String
• use Integer.ParseInt() to convert to Integer
HTTP Message Structure
• A HTTP message has the following structure:
Request/Status-Line \r\n
Header1: value1 \r\n
Header2: value2 \r\n
...
HeaderN: valueN \r\n
\r\n

Message-Body
Reading HTTP Messages
• Several ways to interpret the bytes of the body
• Binary: images, compressed files, class files, ...
• Text: ASCII, Latin-1, UTF-8, ...
• Commonly, applications parse the headers of the
message, and process the body according to the
information supplied by the headers
• E.g., Content-Type, Content-Encoding, Transfer-Encoding

27
An Example
Parsing the Headers
• So how are the headers themselves represented?
• Headers of a HTTP message must be in
US-ASCII format (1 byte per character)
Example: Extracting the Headers
Socket socket = new Socket(argv[0], 80);
InputStream istream = socket.getInputStream();
OutputStream ostream = socket.getOutputStream();

String request = "GET / HTTP/1.1\r\n" +


"Host: " + argv[0] + "\r\n" +
"Connection: close\r\n\r\n";
ostream.write(request.getBytes());

StringBuffer headers = new StringBuffer(); int byteRead = 0;


while ( !endOfHeaders(headers) &&
(byteRead = istream.read()) >= 0) {
headers.append((char) byteRead); }
System.out.print(headers);
socket.close();
Example: Extracting the Headers (cont)
public static boolean endOfHeaders(StringBuffer headers) {

int lastIndex = headers.length() - 1;

if (lastIndex < 3 || headers.charAt(lastIndex) != '\n')


return false;

return (headers.substring(lastIndex - 3, lastIndex + 1)


.equals("\r\n\r\n"));
}

• Why did we (inefficiently) read one byte at a time?


• Is there any way to avoid this inefficiency?
Persistent Connections
• According to HTTP/1.1, a server does not have to close the connection
after fulfilling your request
• One connection (socket) can be used for several requests and
responses send more requests
• even while earlier responses are being transferred (pipelining)
• saves “slow start” time
• How can the client know when one response ends and a new one
begins?
• To avoid persistency, require explicitly by the header Connection:
close
Parsing URLs
Working with URLs
• URL (Uniform/Universal Resource Locator): a reference (address) to a
resource on the Internet
http://www.mait.ac.il : 80/~java/main.html#notes

Protoco
l
Host Port File
Reference
Name Numbe Nam
r e
Query

http://www.google.com/search?hl=en&q=java+mait&btnG=Search
34
The Class URL
• The class URL is used for parsing URLs
• Constructing URLs:
• URL w3c1 = new URL("http://www.w3.org/TR/");
• URL w3c2 = new URL("http","www.w3.org",80,"TR/");
• URL w3c3 = new URL(w3c2, "xhtml1/");
• If the string is not an absolute URL, then it is considered relative to the
URL

35
Parsing URLs
• The following methods of URL can be used for parsing URLs
getProtocol(), getHost(), getPort(), getPath(), getFile(), getQuery(),
getRef()

36
URLEncoder
• Contains a utility method encode for converting a string
into an encoded format (used in URLs, e.g. for searches)
• To convert a string, each char is examined in turn:
• Space is converted into a plus sign +
• a-z, A-Z, 0-9, ., -, * and _ remain the same.
• The bytes of all special characters are replaced by hexadecimal
numbers, preceded with %
• To decode an encoded string, use decode() of the class
URLDecoder

37
Class URLConnection
High-Level Networking
The class URLConnection
• To establish the actual resource, we can use the object
URLConnection obtained by url.openConnection()
• If the protocol of the URL is HTTP, the returned object is of class
HttpURLConnection
• This class encapsulates all socket management and HTTP directions
required to obtain the resource

39
public class ContentExtractor {

public static void main(String[] argv) throws Exception {


URL url = new URL(argv[0]);

System.out.println("Host: " + url.getHost());


System.out.println("Protocol: " + url.getProtocol());
System.out.println("----");

URLConnection con = url.openConnection();


InputStream stream = con.getInputStream();

byte[] data = new byte[4096]; int bytesRead = 0;


while((bytesRead=stream.read(data))>=0) {
System.out.write(data,0,bytesRead);
}}}
40
About URLConnection
• The life cycle of a URLConnection object has two parts:
• Before actual connection establishment
• Connection configuration
• After actual connection establishment
• Content retrieval
• Passage from the first phase to the second is implicit
• A result of calling some committing methods, like getDate()

41
About HttpURLConnection
• The HttpURLConnection class encapsulates all HTTP
transaction over sockets, e.g.,
• Content decoding
• Redirection
• Proxy indirection
• You can control requests by its methods
• setRequestMethod, setFollowRedirects,
setRequestProperty, ...

42

You might also like