Socket s = new Socket("www.arsdigita.com",80);
S: (listens at TCP port 119)
C: (requests connection on TCP port 119)
S: 200 wombatvax news server ready - posting ok
(client asks for a current newsgroup list)
C: LIST
S: 215 list of newsgroups follows
S: net.wombats 00543 00501 y
S: net.unix-wizards 10125 10011 y
(more information here)
S: net.idiots 00100 00001 n
S: .
(client selects a newsgroup)
C: GROUP net.unix-wizards
S: 211 104 10011 10125 net.unix-wizards group selected
(there are 104 articles on file, from 10011 to 10125)
(client selects an article to read)
C: STAT 10110
S: 223 10110 <23445@sdcsvax.ARPA> article retrieved - statistics
only (article 10110 selected, its message-id is
<23445@sdcsvax.ARPA>)
(client examines the header)
C: HEAD
S: 221 10110 <23445@sdcsvax.ARPA> article retrieved - head
follows (text of the header appears here)
S: .
(client wants to see the text body of the article)
C: BODY
S: 222 10110 <23445@sdcsvax.ARPA> article retrieved - body
follows (body text here)
S: .
(client selects next article in group)
C: NEXT
S: 223 10113 <21495@nudebch.uucp> article retrieved - statistics
only (article 10113 was next in group)
(client finishes session)
C: QUIT
S: 205 goodbye.
GET /path/to/file.html HTTP/1.0followed by 2 newline characters '\n'. (Of course /path/to/file.html is the actual file path including any query string info).
class Download{
public static void main(String[] args){
Socket s = null;
PrintWriter fout;
BufferedReader fin;
try{
s = new Socket(args[0],80);
System.out.println("connected");
fout = new PrintWriter(
new OutputStreamWriter(s.getOutputStream()));
fin = new BufferedReader(
new InputStreamReader(s.getInputStream()));
String path = "GET " + args[1] + " HTTP/1.0\n\n";
// send GET
fout.print(path);
// Must flush or command never gets sent!!
fout.flush();
//read response
String line;
System.out.println("sent request");
while((line = fin.readLine()) != null){
System.out.println(line);
}
s.close();
}
catch(IOException e){
System.out.println("Cannot connect");
}
}
}
// Create listener on port 2000 ServerSocket ss = new ServerSocket(2000); // Starts listening on server socket. THis call block until a client // connects. It returns with the connected socket. The server socket // remains alive, but will not accept more connections until another // call to accept(). Socket s = ss.accept(); // get Input and Output streams on s, and perform server app.
Below is a short program which prints out the host name and IP address of the machine on which it is run.
import java.io.*;
import java.net.*;
class MyAddr{
public static void main(String[] args){
try{
InetAddress in = InetAddress.getLocalHost();
System.out.println(in.getHostName());
System.out.println(in.getHostAddress());
}
catch(IOException e){
}
}
}