Internet-Network Programming W13
Internet-Network Programming W13
Programming
BSCS-4
Manipulating URLs
• URL is an acronym for Uniform Resource Locator and is a reference (an address) to a
resource on the Internet.
• Sample structure of a URL. The resource name part may contain: host name, file name,
port number(optional) and reference (optional)
http://scholar.google.com.pk
• We can create a URL object in Java from an absolute URL or a relative URL.
• The URL class provides several methods implemented on URL objects. You
can get the protocol, host name, port number, and filename from a URL.
Example code
import java.net.*;
System.out.println("protocol = “ + aURL.getProtocol());
System.out.println("host = " + aURL.getHost());
System.out.println("filename = " + aURL.getFile());
System.out.println("port = " + aURL.getPort());
System.out.println("ref = " + aURL.getRef());
}
}
Connecting with a URL (1)
openStream(): returns a java.io.InputStream object, from which you can read
easily as reading from an input stream. It may throw an IOException
Example code
import java.net.*;
import java.io.*;
• The URLConnection class provides many methods to communicate with the URL, such as
reading and writing.
Sockets
• Sometimes you need a low-level network communication, such as a client-server
application
• The TCP protocol provides a reliable point-to-point communication channel via
the sockets.
outToClient.close();
socket.close();
server_socket.close();
}
catch(Exception e) {
System.out.print("Whoops! It didn't work!\n");
} }}
A simple server/client pair example (cont.)
The client side
import java.lang.*;
import java.io.*;
import java.net.*;
class Client {
public static void main(String args[]) {
try {
Socket socket = new Socket("localhost", 1234);
inFromServer.close();
}
catch(Exception e) {
System.out.print("Whoops! It didn't work!\n");
}}}
A simple server/client pair example (cont.)
• What happens on the screen if you run the code?
• First run Server.java