Beruflich Dokumente
Kultur Dokumente
Unit II
No. of Hours: 2
InetAddress
continued
URL
URLConnection
continued
Socket
DatagramSocket
Finding an IP Address
InetAddress
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
Socket Communication
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
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
Socket
Socket
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() );
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();
}