Sie sind auf Seite 1von 28

Networking

InetAddress, TCP/IP Sockets

Unit II
No. of Hours: 2

OSI and TCP/IP Layers

ISO (International Standards Organization) has created a


layered model, called the OSI (Open Systems
Interconnect)
TCP/IP (Transmission Control Protocol / Internet
Protocol) already developed

Basic Networking Classes

The J2SE documentation for java.net lists


over 30 classes. A few of the key ones:

InetAddress

the class that represents IP addresses and


contains operations for manipulating them

continued

Basic Networking Classes

URL

used to retrieve the Web page at the given URL

URLConnection

also used to retrieve a Web page


allows extra parameters to be sent to the URL

e.g HTTP request headers

continued

Basic Networking Classes

Socket

the client-side socket class for TCP


ServerSocket

the server-side socket class for TCP

DatagramSocket

allows a client or server to send/receive UDP


packets

Finding an IP Address

Javas InetAddress class makes the mapping


between hostnames and IP addresses much
easier than in UNIX.

For details, look at the the documentation for


java.net.InetAddress

InetAddress

static InetAddress[] getAllByName(String host)


Given the name of a host, returns an array of its IP
addresses, based on the configured name service on the system.
static InetAddress getByAddress(byte[] addr)
Returns an InetAddress object given the raw IP address .
static InetAddress getByAddress(String host, byte[] addr)
Create an InetAddress based on the provided host name
and IP address No name service is checked for the validity of the
address.
static InetAddress getByName(String host)
Determines the IP address of a host, given the host's
name.
static InetAddress getLocalHost()
Returns the local host.

InetAddress

byte[] getAddress()
Returns the raw IP address of this InetAddress object.
String getHostAddress()
Returns the IP address string in textual presentation.
String getHostName()
Gets the host name for this IP address.
boolean isMulticastAddress()
Utility routine to check if the InetAddress is an IP multicast
address.
Boolean isReachable(int timeout)
Test whether that address is reachable.

WhatIP.java
import java.io.*;
import java.net.*;
public class WhatIP
{
public static void main(String args[])
throws IOException
{
InetAddress addr =
InetAddress.getByName(machinename);
System.out.println("Inet address is "+ addr);
System.out.println("\naddr.getHostName():: " +
addr.getHostName());
System.out.println("\naddr.getLocalHost() :: " +
addr.getLocalHost());
System.out.println("\naddr.getAddress() :: " +
addr.getAddress());
System.out.println("\naddr.isMulticastAddress() :: " +
addr.isMulticastAddress());
}
}

Output

Sockets

Sockets provide an interface for programming networks at the


transport layer.
Network communication using Sockets is very much similar to
performing file I/O
In fact, socket handle is treated like file handle.
The streams used in file I/O operation are also applicable to
socket-based I/O
Socket-based communication is programming language
independent.
That means, a socket program written in Java language can also
communicate to a program written in Java or non-Java socket
program.

Socket Communication

A server (program) runs on a specific


computer and has a socket that is bound to a
specific port. The server waits and listens to
the socket for a client to make a connection
request.

port

server

Connection request
Client

Socket Communication
If everything goes well, the server accepts the connection. Upon
acceptance, the server gets a new socket bounds to a different
port. It needs a new socket (consequently a different port
number) so that it can continue to listen to the original socket for
connection requests while serving the connected client.

port

port

server

port

Connection

Client

Sockets and Java Socket Classes

A socket is an 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 destined to be sent.
Javas .net package provides two classes:

Socket for implementing a client


ServerSocket for implementing a server

ServerSocket
public class ServerSocket extends Object
This class implements server sockets. A server socket
waits for requests to come in over the network. It
performs some operation based on that request,
and then possibly returns a result to the requester.
The actual work of the server socket is performed by
an instance of the SocketImpl class. An application
can change the socket factory that creates the
socket implementation to configure itself to create
sockets appropriate to the local firewall.

ServerSocket

Socket accept()
Listens for a connection to be made to this socket and accepts it.
Void bind(SocketAddress endpoint)
Binds the ServerSocket to a specific address (IP address and port number).
Void close()
Closes this socket.
ServerSocketChannel getChannel()
Returns the unique ServerSocketChannel object associated with this socket, if any.
InetAddress getInetAddress()
Returns the local address of this server socket.
int getLocalPort()
Returns the port on which this socket is listening.
SocketAddress getLocalSocketAddress()
Returns the address of the endpoint this socket is bound to, or null if it is not bound
yet.
Int getReceiveBufferSize()
Gets the value of the SO_RCVBUF option for this ServerSocket, that is the proposed
buffer size that will be used for Sockets accepted from this ServerSocket.
Boolean getReuseAddress()
Tests if SO_REUSEADDR is enabled.

ServerSocket

Int getSoTimeout()
Retrieve setting for SO_TIMEOUT.protected
Void implAccept(Socket s)
Subclasses of ServerSocket use this method to override accept() to return their own subclass of
socket.
Boolean isBound()
Returns the binding state of the ServerSocket.
Boolean isClosed()
Returns the closed state of the ServerSocket.
Void setPerformancePreferences(int connectionTime, int latency, int bandwidth)
Sets performance preferences for this ServerSocket.
Void setReceiveBufferSize(int size)
Sets a default proposed value for the SO_RCVBUF option for sockets accepted from this
ServerSocket.
Void setReuseAddress(boolean on)
Enable/disable the SO_REUSEADDR socket option.static
Void setSocketFactory(SocketImplFactory fac)
Sets the server socket implementation factory for the application.
Void setSoTimeout(int timeout)
Enable/disable SO_TIMEOUT with the specified timeout, in milliseconds.
String toString()
Returns the implementation address and implementation port of this socket as a String.

Socket

public class Socket extends Object


This class implements client sockets (also
called just "sockets"). A socket is an endpoint
for communication between two machines.
The actual work of the socket is performed by
an instance of the SocketImpl class. An
application, by changing the socket factory
that creates the socket implementation, can
configure itself to create sockets appropriate
to the local firewall.

Socket

void bind(SocketAddress bindpoint)


Binds the socket to a local address.
Void close()
Closes this socket.
Void connect(SocketAddress endpoint)
Connects this socket to the server.
Void connect(SocketAddress endpoint, int timeout)
Connects this socket to the server with a specified timeout value.
SocketChannel getChannel()
Returns the unique SocketChannel object associated with this socket, if any.
InetAddress getInetAddress()
Returns the address to which the socket is connected.
InputStream getInputStream()
Returns an input stream for this socket.
Boolean getKeepAlive()
Tests if SO_KEEPALIVE is enabled.
InetAddress getLocalAddress()
Gets the local address to which the socket is bound.
int getLocalPort()
Returns the local port to which this socket is bound.
SocketAddress getLocalSocketAddress()
Returns the address of the endpoint this socket is bound to, or null if it is not bound yet.

Socket

Void setReceiveBufferSize(int size)


Sets the SO_RCVBUF option to the specified value for this
Socket.
Void setReuseAddress(boolean on)
Enable/disable the SO_REUSEADDR socket option.
Void setSendBufferSize(int size)
Sets the SO_SNDBUF option to the specified value for this
Socket.static
Void setSocketImplFactory(SocketImplFactory fac)
Sets the client socket implementation factory for the application.
Void shutdownInput()
Places the input stream for this socket at "end of stream".
Void shutdownOutput()
Disables the output stream for this socket.
String toString()
Converts this socket to a String.

Java Sockets
ServerSocket(1234)
Server

Output/write stream

Client

Input/read stream
Socket(128.250.25.158, 1234)
It can be host_name like google.com

Implementing a Server
1. Open the Server Socket:
ServerSocket server;
DataOutputStream os;
DataInputStream is;
server = new ServerSocket( PORT );
2. Wait for the Client Request:
Socket client = server.accept();
3. Create I/O streams for communicating to the client
is = new DataInputStream( client.getInputStream() );
os = new DataOutputStream( client.getOutputStream()
);
4. Perform communication with client
Receive from client: String line = is.readLine();
Send to client: os.writeBytes("Hello\n");
5. Close sockets: client.close();

Implementing a Client
1. Create a Socket Object:
client = new Socket( server, port_id );
2. Create I/O streams for communicating with the server.
is = new DataInputStream(client.getInputStream() );
os = new DataOutputStream( client.getOutputStream() );

3. Perform I/O or communication with the server:


Receive data from the server:
String line = is.readLine();
Send data to the server:
os.writeBytes("Hello\n");
4. Close the socket when done:
client.close();

SimpleServer
// SimpleServer.java: a simple server program
import java.net.*;
import java.io.*;
public class SimpleServer {
public static void main(String args[]) throws IOException {
// Register service on port 1234
ServerSocket s = new ServerSocket(1234);
Socket s1=s.accept(); // Wait and accept a connection
// Get a communication stream associated with the socket
OutputStream s1out = s1.getOutputStream();
DataOutputStream dos = new DataOutputStream (s1out);
// Send a string!
dos.writeUTF("Hi there");
// Close the connection, but not the server socket
dos.close();
s1out.close();
s1.close();
}
}

SimpleClient
// SimpleClient.java: a simple client program
import java.net.*;
import java.io.*;
public class SimpleClient {
public static void main(String args[]) throws IOException {
// Open your connection to a server, at port 1234
Socket s1 = new Socket("lappu",1234);
// Get an input file handle from the socket and read the input
InputStream s1In = s1.getInputStream();
DataInputStream dis = new DataInputStream(s1In);
String st = new String (dis.readUTF());
System.out.println(st);
// When done, just close the connection and exit
dis.close();
s1In.close();
s1.close();
}
}

Output

Socket Exceptions
try {
Socket client = new Socket(host, port);
handleConnection(client);
}
catch(UnknownHostException uhe) {
System.out.println("Unknown host: " + host);
uhe.printStackTrace();
}
catch(IOException ioe) {
System.out.println("IOException: " + ioe);
ioe.printStackTrace();
}

ServerSocket & Exceptions

public ServerSocket(int port) throws IOException


Creates a server socket on a specified port.
A port of 0 creates a socket on any free port. You can use
getLocalPort() to identify the (assigned) port on which this
socket is listening.
The maximum queue length for incoming connection indications
(a request to connect) is set to 50. If a connection indication
arrives when the queue is full, the connection is refused.
Throws:
IOException - if an I/O error occurs when opening the socket.
SecurityException - if a security manager exists and its
checkListen method doesn't allow the operation.

Das könnte Ihnen auch gefallen