Vous êtes sur la page 1sur 34

INTRODUCTION

Sockets are at the foundation of modern networking


because a socket allows a single computer to serve many
different clients at once, as well as to serve many different
types of information.

A port is a numbered socket on a particular machine.

A server process is said to listen to a port until a client


connects to it.

A server is allowed to accept multiple clients connected to


the same port number, although each session is unique.

To manage multiple client connections, a server process


must be multithreaded.
INTRODUCTION
Socket communication takes place via a protocol.

Internet Protocol (IP)


Breaks data into small packets and sends them
to an address across a network.
Does not guarantee to deliver said packets to the
destination.

Transmission Control Protocol (TCP)


Manages to robustly string together the packets.
sorting and retransmitting them as necessary to
reliably transmit data.

User Datagram Protocol (UDP)


Can be used directly to support fast,
connectionless, unreliable transport of packets.
Networking Classes and Interfaces

Java supports both the TCP and UDP protocol families.

TCP is used for reliable stream-based I/O across the


network.

UDP supports a simpler, hence faster, point-to-point


datagram-oriented model.

The classes contained in the java.net package are:

InetAddress
Socket
ServerSocket
Networking Classes and Interfaces

InetSocketAddress
SocketAddress
CookieHandler
SocketPermission
CookieManager
DatagramPacket
DatagramSocket
URL
URI
MulticastSocket
Networking Classes and Interfaces
The java.net packages interfaces are :

ContentHandlerFactory
DatagramSocketImplFactory
SocketOptions
CookiePolicy
FileNameMap
CookieStore
SocketImplFactory
URLStreamHandlerFactory
InetAddress

The InetAddress class is used to encapsulate both the


numerical IP address and the domain name for that
address.

Interaction with InetAddress class by using the name of


an IP host, rather than its IP address.

InetAddress can handle both IPv4 and IPv6 addresses.

There are three commonly used InetAddress factory


methods.
InetAddress-Factory Methods

To create an InetAddress object, we have to use one of


the available factory methods.

Factory methods are merely a convention whereby static


methods in a class return an instance of that class.

There are three commonly used InetAddress factory


methods.

getLocalHost( )
getByName(String hostName)
getAllByName(String hostName)
InetAddress-Factory Methods
static InetAddress getLocalHost( )
throws UnknownHostException

Returns the InetAddress object that represents


the local host.
If the method is unable to resolve the host name,
they throw an UnknownHostException.

static InetAddress getByName(String hostName)


throws UnknownHostException

Returns an InetAddress for a host name passed


to it.
If the method is unable to resolve the host name,
they throw an UnknownHostException.
InetAddress-Factory Methods
static InetAddress[ ] getAllByName(String hostName)
throws UnknownHostException

Returns an array of InetAddresses that represent


all of the addresses that a particular name
resolves to.
It will also throw an UnknownHostException if it
cant resolve the name to at least one address.
InetAddress-Example
import java.net.*;
class InetAddressTest{
public static void main(String args[]) throws
UnknownHostException {
InetAddress Address = InetAddress.getLocalHost();
System.out.println(Address);
Address = InetAddress.getByName(gmail.com");
System.out.println(Address);
InetAddress iaddress[ ] =
InetAddress.getAllByName("www.gmail.com");
for (int i=0; i< iaddress.length; i++)
System.out.println(iaddress[i]);
}
}

Output (Of course, the output you see may be slightly different.)
vikash-desktop/127.0.1.1
gmail.com/216.58.220.37
www.gmail.com/216.58.220.37
InetAddress- Instance Methods

Inet4Address - represents a traditional-style IPv4 address.

Inet6Address - encapsulates a new-style Ipv6 address.

Inet4Address and Inet6Address are subclasses of InetAddress.


TCP/IP Client Sockets
TCP/IP sockets are used to implement stream-based
connections between hosts on the Internet.

A socket can be used to connect Javas I/O system to


other programs that may reside either on the local machine
or on any other machine on the Internet.

There are two kinds of TCP sockets in Java. One is for


servers, and the other is for clients.

ServerSocket class is for servers.

The Socket class is for clients.


TCP/IP Client Sockets
There are two constructors used to create client sockets:
Socket- Instance Methods

Connect( ) - which allows you to specify a new connection.

IsConnected( ) - which returns true if the socket is connected to a server.

IsBound( ) - which returns true if the socket is bound to an address.

IsClosed( ) - which returns true if the socket is closed.


import java.io.*;
import java.net.InetAddress;
import java.net.Socket;

public class Client


{
private static Socket socket;

public static void main(String args[])


{
try
{
String host = "localhost";
int port = 5555;
InetAddress address = InetAddress.getByName(host);
socket = new Socket(address, port);

//Send the message to the server


OutputStream os = socket.getOutputStream();
OutputStreamWriter osw = new OutputStreamWriter(os);
BufferedWriter bw = new BufferedWriter(osw);

String number = "2";

String sendMessage = number + "\n";


bw.write(sendMessage);
bw.flush();
System.out.println("Message sent to the server : "+sendMessage);
//Get the return message from the server
InputStream is = socket.getInputStream();
InputStreamReader isr = new InputStreamReader(is);
BufferedReader br = new BufferedReader(isr);

String message = br.readLine();

System.out.println("Message received from the server : " +message);


}
catch (Exception exception)
{
exception.printStackTrace();
}
finally
{
//Closing the socket
try
{
socket.close();
}
catch(Exception e)
{
e.printStackTrace();
}
}
}
}
ServerSocket- Instance Methods

The ServerSocket class is used to create servers that listen


for either local or remote client programs to connect to them on
published ports.

When we create a ServerSocket, it will register itself with the


system as having an interest in client connections.

The constructors for ServerSocket reflect the port number


that we want to accept connections on and, optionally, how
long we want the queue for said port to be.

The queue length tells the system how many client


connections it can leave pending before it should simply refuse
connections.

The default is 50.


ServerSocket- Instance Methods
The ServerSocket class is used to create servers that listen for either local or remote client
programs to connect to them on published ports.

When we create a ServerSocket, it will register itself with the system as having an interest
in client connections.

The constructors for ServerSocket reflect the port number that we want to accept
connections on and, optionally, how long we want the queue for said port to be.

The queue length tells the system how many client connections it can leave pending before
it should simply refuse connections.

The default is 50.

Constructors:
accept() - ServerSocket has a method called accept( ), which is a blocking call that will
wait for a client to initiate communications and then return with a normal Socket that is
then used for communication with the client.

import java.net.ServerSocket;
import java.net.Socket;
import java.io.*;

public class Server


{
private static Socket socket;
public static void main(String[] args){
try{
int port = 5555;
ServerSocket serverSocket = new ServerSocket(port);
System.out.println("Server Started and listening to the port 25003");
//Server is running always. This is done using this while(true) loop
while(true){
//Reading the message from the client
socket = serverSocket.accept();
InputStream is = socket.getInputStream();
InputStreamReader isr = new InputStreamReader(is);
BufferedReader br = new BufferedReader(isr);

String number = br.readLine();


System.out.println("Message received from client is "+number);
//Multiplying the number by 2 and forming the return message
String returnMessage;
try{
int numberInIntFormat = Integer.parseInt(number);
int returnValue = numberInIntFormat*2;
returnMessage = String.valueOf(returnValue) + "\n";
}
catch(NumberFormatException e){
//Input was not a number. Sending proper message back to client.
returnMessage = "Please send a proper number\n";
}
//Sending the response back to the client.
OutputStream os = socket.getOutputStream();
OutputStreamWriter osw = new OutputStreamWriter(os);
BufferedWriter bw = new BufferedWriter(osw);

bw.write(returnMessage);
System.out.println("Message sent to the client is "+returnMessage);
bw.flush();
}
}
catch (Exception e){
e.printStackTrace();
}
finally{
try{
socket.close();
}
catch(Exception e){}
Datagrams are bundles of information passed between machines.

Once the datagram has been released to its intended target, there is no assurance that it will
arrive or even that someone will be there to catch it.

when the datagram is received, there is no assurance that it hasnt been damaged in transit
or that whoever sent it is still there to receive a response.

Java implements datagrams on top of the UDP protocol by using two classes:

DatagramPacket - object of this class is used for data container.

DatagramSocket - is the mechanism used to send or receive the DatagramPackets.

DatagramSocket

DatagramSocket defines four public constructors.

DatagramSocket( ) throws SocketException


creates a DatagramSocket bound to any unused port on the local computer.

DatagramSocket(int port) throws SocketException


creates a DatagramSocket bound to the port specified by port.
DatagramSocket(int port, InetAddress ipAddress) throws SocketException
bound to the specified port and InetAddress

DatagramSocket(SocketAddress address) throws SocketException


bound to the specified SocketAddress.

SocketAddress is an abstract class that is implemented by the concrete class


InetSocketAddress. InetSocketAddress encapsulates an IP address with a port number.

DatagramSocket defines many methods.

void send(DatagramPacket packet) throws IOException


The send( ) method sends packet to the port specified by packet.

void receive(DatagramPacket packet) throws IOException


The receive method waits for a packet to be received from the port specified by packet
and returns the result.
DatagramPacket

DatagramPacket defines several constructors.

DatagramPacket(byte data[ ], int size)


specifies a buffer that will receive data and the size of a packet. It is used for receiving data
over a DatagramSocket.

DatagramPacket(byte data[ ], int offset, int size)


specify an offset into the buffer at which data will be stored.

DatagramPacket(byte data[ ], int size, InetAddress ipAddress, int port)


specifies a target address and port, which are used by a DatagramSocket to determine
where the data in the packet will be sent.

DatagramPacket(byte data[ ], int offset, int size, InetAddress ipAddress, int port)
transmits packets beginning at the specified offset into the data.
import java.io.*;
import java.net.*;

class UDPClient
{
public static void main(String args[]) throws Exception
{
BufferedReader inFromUser =
new BufferedReader(new InputStreamReader(System.in));
DatagramSocket clientSocket = new DatagramSocket();
InetAddress IPAddress = InetAddress.getByName("localhost");
byte[] sendData = new byte[1024];
byte[] receiveData = new byte[1024];
String sentence = inFromUser.readLine();
sendData = sentence.getBytes();
DatagramPacket sendPacket = new DatagramPacket(sendData, sendData.length,
IPAddress, 9875);
clientSocket.send(sendPacket);
DatagramPacket receivePacket = new DatagramPacket(receiveData,
receiveData.length);
clientSocket.receive(receivePacket);
String modifiedSentence = new String(receivePacket.getData());
System.out.println("FROM SERVER:" + modifiedSentence);
clientSocket.close();
}
}
import java.io.*;
import java.net.*;

class UDPServer
{
public static void main(String args[]) throws Exception
{
DatagramSocket serverSocket = new DatagramSocket(9875);
byte[] receiveData = new byte[1024];
byte[] sendData = new byte[1024];
while(true)
{
DatagramPacket receivePacket = new DatagramPacket(receiveData,
receiveData.length);
serverSocket.receive(receivePacket);
String sentence = new String( receivePacket.getData());
System.out.println("RECEIVED: " + sentence);
InetAddress IPAddress = receivePacket.getAddress();
int port = receivePacket.getPort();
String capitalizedSentence = sentence.toUpperCase();
sendData = capitalizedSentence.getBytes();
DatagramPacket sendPacket =
new DatagramPacket(sendData, sendData.length, IPAddress, port);
serverSocket.send(sendPacket);
}
}
}
DatagramPacket defines several
methods
Uniform Resource Locator (URL)

URL is used to locate all the resources of the Net.

We can reliably name anything using URL.

The URL provides a way to uniquely identify or address information on the Internet.

Every browser uses them to identify information on the Web.

URL class provides a simple, concise API to access information across the Internet
using URLs.

All URLs share the same basic format:

http://www.gmail.com:80/index.html

Protocol Host Name or IP Address Port No Actual File


Constructors of URL

URL(String urlSpecifier) throws MalformedURLException


http://www.gmail.com------------------String

URL(String protocolName, String hostName, int port, String path)


throws MalformedURLException
allow you to break up the URL into its component parts

URL(String protocolName, String hostName, String path)


throws MalformedURLException
allow you to break up the URL into its component parts

URL(URL urlObj, String urlSpecifier) throws MalformedURLException


allows you to use an existing URL as a reference context and then create a new URL
from that context.
// Demonstrate URL.
import java.net.*;
class URLDemo {
public static void main(String args[]) throws MalformedURLException {
URL hp = new URL("http://www.osborne.com/downloads");
System.out.println("Protocol: " + hp.getProtocol());
System.out.println("Port: " + hp.getPort());
System.out.println("Host: " + hp.getHost());
System.out.println("File: " + hp.getFile());
System.out.println("Ext:" + hp.toExternalForm());
}
}

Protocol: http
Port: -1
Host: www.osborne
File: /downloads
Ext:http://www.osborne/downloads

Thus, given a URL object, we can retrieve the data associated with it.

To access the content information of a URL, create a URLConnection object from it, using its
openConnection( ) method,
openConnection( ) has the following general form:
URLConnection openConnection( ) throws IOException

It returns a URLConnection object associated with the invoking URL object.

URLConnection

URLConnection class is used to access the attributes of a remote resource.

Once we make a connection to a remote server, we can use URLConnection to inspect the
properties of the remote object before transporting it locally.

URLConnection defines several methods.


// Demonstrate URLConnection.
import java.net.*;
import java.io.*;
import java.util.Date;
class UCDemo
{
public static void main(String args[]) throws Exception {
int c;
URL hp = new URL("http://www.internic.net");
URLConnection hpCon = hp.openConnection();
// get date
long d = hpCon.getDate();
if(d==0)
System.out.println("No date information.");
else
System.out.println("Date: " + new Date(d));
// get content type
System.out.println("Content-Type: " +
hpCon.getContentType());
// get expiration date
d = hpCon.getExpiration();
if(d==0)
System.out.println("No expiration information.");
else
System.out.println("Expires: " + new Date(d));
// get last-modified date
d = hpCon.getLastModified();
if(d==0)
System.out.println("No last-modified information.");
else
System.out.println("Last-Modified: " + new Date(d));
// get content length
int len = hpCon.getContentLength();
if(len == -1)
System.out.println("Content length unavailable.");
else
System.out.println("Content-Length: " + len);
if(len != 0) {
System.out.println("=== Content ===");
InputStream input = hpCon.getInputStream();
int i = len;
while (((c = input.read()) != -1)) { // && (--i > 0)) {
System.out.print((char) c);
}
input.close();
} else {
System.out.println("No content available.");
}
}
Step1: Write through the keyboard into the Step1: Create a packet for the server.
buffer. (DatagrtamSocket).
Step2: Create a socket for client(Since UDP Step2: Create a packet (receive packet).
so DatagramSocket)
Step3: Receive the packet.
Step3: Read data from buffer.
Step4: Get the data from the received packet.
Step4: Convert the data into bytes.
Step5: Get the address and port number from
Step5: Create a packet (send packet) the received packet.
[The packet should contain data, size of data,
IP address and port number] Step6: Create a packet (send packet) with
the modified data.
Step6: Send the packet.
Step7: Send the packet.
Step7: Create a packet (receive packet)
Step8: Receive the packet.
Step9: Get the modified data from the
received packet.

Vous aimerez peut-être aussi