The java.net package is centered around the Socket class, which represents a connection to another
socketpossibly on another machineacross which bytes can flow. You typically create a socket with a host
name or InetAddress and a port number. You can also specify a local InetAddress and port to which
the socket will be bound. A ServerSocket class lets you listen on a port for incoming connection requests,
creating a socket for each request. For example, the following program accepts input on a socket:
import java.net.;
import java.io.;
public class AcceptInput {
public static final int PORT = 0xCAFE;
public static void main(String[] args)
throws IOException
{
ServerSocket server = new ServerSocket(PORT);
byte[] bytes = new byte[1024];
for (;;) {
try {
System.out.println("---------------------");
Socket sock = server.accept();
InputStream in = sock.getInputStream();
int len;
while ((len = in.read(bytes)) > 0)
System.out.write(bytes, 0, len);
in.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
This program creates a ServerSocket and repeatedly accepts connections to it. The Socket obtained for
each connection is queried for an input stream and the data from that socket is read from the stream and
written to the standard output stream, printing whatever bytes it receives. A client that shipped its standard
input to the server might look like this:
import java.net.;
import java.io.;
public class WriteOutput {
public static void main(String[] args)
throws IOException
{
String host = args[0];
Socket sock = new Socket(host, AcceptInput.PORT);
OutputStream out = sock.getOutputStream();
int ch;
while ((ch = System.in.read()) != -1)
out.write(ch);
out.close();
}
}
Once we have the actual Socket connection, I/O is performed, like all other I/O, using an appropriate input
or output stream.