Parsing a URL
try {
URL url = new URL("http://hostname:80/index.html#_top_");
String protocol = url.getProtocol(); // http
String host = url.getHost(); // hostname
int port = url.getPort(); // 80
String file = url.getFile(); // index.html
String ref = url.getRef(); // _top_
} catch (MalformedURLException e) { }
Reading Text from a URL
try {
URL url = new URL("http://hostname:80/index.html");
BufferedReader in = new BufferedReader(new InputStreamReader(url.openStream()));
String str;
while ((str = in.readLine()) != null) {
process(str);
}
in.close();
} catch (MalformedURLException e) {
} catch (IOException e) { }
Resolving a Hostname
Creating a Client Socket
try {
InetAddress addr = InetAddress.getByName("java.sun.com");
int port = 80;
Socket sock = new Socket(addr, port);
} catch (IOException e) {
}
Creating a Server Socket
try {
int port = 2000;
ServerSocket srv = new ServerSocket(port);
// Wait for connection from client.
Socket socket = srv.accept();
} catch (IOException e) {
}
Reading Text from a Socket
try {
BufferedReader rd = new BufferedReader(new InputStreamReader(socket.getInputStream()));
String str;
while ((str = rd.readLine()) != null) {
process(str);
}
rd.close();
} catch (IOException e) {
}
Subscribe to:
Post Comments (Atom)
No comments:
Post a Comment