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.
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: http://download.oracle.com/javase/6/docs/api/java/net/Socket.html
- It represents network connections.
- It supports stream-based (TCP) communications.
- You need to specify the remote host name and port when you creae a Socket.
- It will automatically get a free local port upon connection (if you don't specify a local port for it).
- Constructors and main methods
// Constructors
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;
// Methods
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
1) Open a Socket with remote host name and port
2) Invoke getInputStream & getOutputStream to obtain I/O streams
3) Read/write the streams according to protocol
5) Close the socket
Client applications make use of the classes Socket, InputStream and OutputStream. The operations of a client are:
1) Create a socket by using one of the constructors of the Socket class. You must specify the host name (or the IP address) and the port number of the target remote server. Your attempt is successful when the target server accepts your connection request.
2) Once you create a Socket object, you use that object’s two methods, getInputStream and getOutputStream, to establish input stream and output streams to the socket. These two streams enable you to transmit data between the client and the server.
3) Read from and write to the streams according to the application-level protocol of the target server. This step will differ from client to client, depending on the server.
4) Close the socket and the streams.
These four steps remain largely the same for many different client programs you are going to write, though the implementation of step 3 varies accordingly to the designated protocol.
Examples of Java TCP client programs
Example 1: Daytime
- Some servers run the daytime service on TCP port 13.
C:\>telnet plbpc.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) {}
}
}
Example 2: QOTD (Quote of the Day)
QOTD Service: A server listens for TCP connections on TCP port 17. Once a connection is established a short message is sent out the connection (and any data received is thrown away). The service closes the connection after sending the quote.
- Some servers run the QOTD service on TCP port 17.
C:\>telnet alpha.mike-r.com 17
C:\>
- It is easy to write a Java QOTD client.
- All the program needs to do is to establish a TCP connection on port 17 of a QOTD server.
- Class Exercise: Based on the Java code in Example 1, write, compile and run a QOTD client.
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");
The InetAddress class
(Not so important!)
API Reference: http://download.oracle.com/javase/6/docs/api/java/net/InetAddress.html
- It provides an 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!");
}
}
}
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.