Creating A URL
Creating A URL
NET
Urls
1. Creating a URL
try {
// With components.
URL url = new URL("http", "hostname", 80, "index.html");
2. Parsing a URL
try {
URL url = new URL("http://hostname:80/index.html#_top_");
This example attempts to retrieve the hostname for an IP address. Note that
getHostName() may not succeed, in which case it simply returns the IP address.
try {
// Get hostname by textual representation of IP address
InetAddress addr = InetAddress.getByName("127.0.0.1");
// Get IP Address
byte[] ipAddr = addr.getAddress();
// Get hostname
String hostname = addr.getHostName();
} catch (UnknownHostException e) {
}
SOCKETS
String str;
while ((str = rd.readLine()) != null) {
process(str);
}
rd.close();
} catch (IOException e) {
}
DATAGRAM
10. Sending a Datagram
public static void send(InetAddress dst, int port, byte[] outbuf,
int len) {
try {
DatagramPacket request = new DatagramPacket(outbuf, len,
dst, port);
DatagramSocket socket = new DatagramSocket();
socket.send(request);
} catch (SocketException e) {
} catch (IOException e) {
}
}
MULTICAST
Once you've created a multicast socket and joined the group, all datagrams sent to its
corresponding multicast address will be available to be read from the socket. You can
read from the socket just like you would from a unicast socket.
public void read(MulticastSocket msocket, byte[] inbuf) {
try {
DatagramPacket packet = new DatagramPacket(inbuf,
inbuf.length);