nc -l 12345
nc hostname 12345
InetAddress
(API documentation)
that has methods for "resolving" domain names into addresses,
and deals with the IPv4 vs IPv6 distinction in the way that, by
now, I hope you expect: InetAddress is a base class, and
Inet4Address are Inet6Address are subclasses. You don't really
need to worry about whether you're using IPv4 or IPv6, because
you typically get InetAddress objects not by calling
constructors, but by calling the method
static InetAddress getByName(String host);which, in one fell-swoop, resolves the domain name host and returns an InetAddress object for it using the appropriate type. This makes it trivial to create a little Java version of the nslookup utility.
Of course, if you were doing this you would handle all the errors and exceptions nicely, wouldn't you ...
There's an asymmetry with sockets (as with phones), in that
one socket waits around for a call to come in (listens), and
the other actually places the call (connects). The Java API
actually has different classes for these different roles.
The class Socket
(API documentation)
represents the client's role, i.e. the one that makes
connection requests.
The class ServerSocket
(API documentation)
represents the server's rolw, i.e. the one that listens for
connection requests.
The important methods of the Socket class for us are:
Socket(InetAddress address, int port) - Creates a stream socket and connects it to the specified port number at the specified IP address. InputStream getInputStream() - Returns an input stream for this socket. void close() - Closes this socket. OutputStream getOutputStream() - Returns an output stream for this socket.So, the key idea is that, once connected, you get InputStream and OutputStream objects for the connection, which means you can use all the same classes and methods that you have for files, byte arrays, and so on.
The following program assumes the command-line argument is the name of a webserver, and it connects on port 80 to that webserver, sends it the basic HTTP GET request for "/", i.e. the front-page of the site, and echos everything it gets right to the terminal.
| NCClient1.java | ReadThread.java |
| WriteThread.java | |