A Network Programming Lecture by Steven Choy
Lecture Overview: The InetAddress class, Overview of using socket, the Socket class, General operations of building a TCP client program, Case study: Daytime service.
The InetAddress class
- Provide abstract access to IP addresses
- No constructor, use static methods for creation
InetAddress getLocalHost() throws UnknownHostException;
InetAddress getByName(String host) throws UnknownHostException;
InetAddress[] getAllByName(String host) throws UnknownHostException;
byte[] getAddress();
String getHostName();
String getHostAddress();
boolean isMulticastAddress();
import java.net.*;
import java.io.*;
public class IPFinder
{
public static void main(String[] args) throws IOException
{
String host;
BufferedReader input =
new BufferedReader(
new InputStreamReader(System.in));
System.out.print("\n\nEnter host name: ");
host = input.readLine();
try
{
InetAddress address = InetAddress.getByName(host);
System.out.println("IP address: " + address.toString());
}
catch (UnknownHostException e)
{
System.out.println("Could not find " + host);
}
}
}
import java.net.*;
public class MyLocalIPAddress
{
public static void main(String[] args)
{
try
{
InetAddress address = InetAddress.getLocalHost();
System.out.println (address);
}
catch (UnknownHostException e)
{
System.out.println("Could not find local address!");
}
}
}
Overview of using socket
- A socket is one end-point of a two-way communication link between two programs running on the network.
- It is through sockets that clients access the network and transmit data.
On the client-side: The client knows the hostname of the machine on which the server is running and the port number on which the server is listening. To make a connection request, the client attempts to contact the server on the given hostname and port. The client also needs to give the server a way to contact it and so it binds to a local port number that it will use during this connection. This is usually assigned by the system. If everything goes well, the server accepts the connection. Upon acceptance, the server binds a new socket with its remote endpoint set to the address and port of the client and the same local endpoint. It also creates a new socket so that it can continue to listen to the original port for connection requests while tending to the needs of the newly-connected client.
The Socket class
- API Reference from java.sun.com: http://java.sun.com/javase/6/docs/api/java/net/Socket.html
- Represent network connections
- Support stream-based (TCP) communications
- Specify the remote host name & port
- Valid port range 1 to 65535
- 1 to 1023 reserved for system services
- Automatically get a free local port upon connection
- Constructors and main methods
Socket(String host, int port) throws IOException;
Socket(InetAddress address, int port) throws IOException;
Socket(String host, int port, InetAddress localAddr, int localPort) throws IOException;
Socket(InetAddress host, int port, InetAddress localAddr, int localPort) throws IOException;
InputStream getInputStream() throws IOException;
OutputStream getOutputStream() throws IOException;
void close() throws IOException;
Socket(String host, int port) – creates a socket and connects it to the specified port on the remote host. The system assigns an available port on the machine as the local port of the socket.
InputStream getInputStream() – returns an input stream of the socket. Reading from this stream obtains data from the remote host.
OutputStream getOutputStream() – returns an output stream of the socket. Writing to this stream transmits data to the remote host.
void close() – closes the socket.
- The Socket class has many other methods for accessing information and setting options of the socket.
- Other useful methods
getInetAddress, getPort, getLocalAddress, getLocalPort, setSoTimeout, getSoTimeout, setTcpNoDelay, getTcpNoDelay, setSoLinger, getSoLinger, setSendBufferSize, getSendBufferSize, setReceiveBufferSize, getReceiveBufferSize, setSocketImplFactory
- Generally speaking, you don’t need to memorize the details of each constructor and method of the Socket class. Whenever necessary, refer to the API documentation
Build a TCP client program - general operations
Case Study: Daytime Service
- Most UNIX servers run the daytime service on TCP port 13.
C:\>telnet www.ouhk.edu.hk 13
Mon Oct 5 13:17:39 2009
遺失與主機的連線。
C:\>
- It is easy to write a Java daytime client.
- All the program needs to do is to establish a TCP connection on port 13 of a remote host.
import java.net.*;
import java.io.*;
import java.util.*;
public class DayTimeClient {
static int dayTimePort = 13;
public static void main(String args[]) {
try {
Socket sock = new Socket(args[0], dayTimePort);
BufferedReader din = new BufferedReader(
new InputStreamReader(sock.getInputStream()));
String rTime = din.readLine();
System.out.println(rTime);
sock.close();
}
catch (Exception e) {}
}
}
Executing socket programs through proxy servers
- Java supports communication via a proxy server in its networking APIs.
- You set the system properties
http.proxyHost and http.proxyPort to the proxy server host and port, respectively, to enable the use of the proxy server.
- It can be done when executing the client program, using the –D switch in the Java command line:
java –Dhttp.proxyHost=<...> –Dhttp.proxyPort=<...> <youClientProgram>
- Alternatively, the system properties can be configured in program code, before creating and using sockets:
System.setProperty("http.proxyHost", "proxy.ouhk.edu.hk");
System.setProperty("http.proxyPort", "8080");
Java Programming Lesson for this lecture
public class IdentifyMyParts {
public static int x = 7;
public int y = 3;
}
1) What are the class variables?
2) What are the instance variables?
3) What is the output from the following code:
IdentifyMyParts a = new IdentifyMyParts();
IdentifyMyParts b = new IdentifyMyParts();
a.y = 5;
b.y = 6;
a.x = 1;
b.x = 2;
System.out.println("a.y = " + a.y);
System.out.println("b.y = " + b.y);
System.out.println("a.x = " + a.x);
System.out.println("b.x = " + b.x);
System.out.println("IdentifyMyParts.x = " + IdentifyMyParts.x);
- What are
System.in and System.out?
System.in - The "standard" input stream. This stream is already open and ready to supply input data. Typically this stream corresponds to keyboard input or another input source specified by the host environment or user.
System.out - The "standard" output stream. This stream is already open and ready to accept output data. Typically this stream corresponds to display output or another output destination specified by the host environment or user.
For simple stand-alone Java applications, a typical way to write a line of output data is:
System.out.println(data)
Thanks for Reading
If you would rather like to have this lecture note in printed format, please click the print action link in the top right corner.
If you find any problem in this lecture note, please feel free to tell Steven via steven@findaway.hk.