Java Reference
In-Depth Information
25.5. java.net The Network
The java.net package provides classes for working with network infra-
structure, such as sockets, network addresses, Uniform Resource Identi-
fiers ( URI s), and Uniform Resource Locators ( URL s).
The java.net package is centered around the Socket class, which repres-
ents 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();
 
Search WWH ::




Custom Search