JAVA TCP/IP Socket Implementation (2)

Client Actions

INSTANTIATE SOCKET OBJECT

  1. Instantiate a Socket object
  2. Communicate with server
    1. Send data/requests
    2. Receive data/replys
  3. Close the socket

Instantiating a socket creates a socket and connects it to the server

Two common constructors

  • arguments are host name and port number
  • arguments are host IP address and port number
import java.net.Socket;
import java.io.IOException;
import java.io.DataInputStream;
import java.io.DataOutputStream;


Socket sock;	// Declare the socket
				// Instantiate the socket using host name and port number
try {
	sock = new Socket("ephebe.anu.edu.au", 13214);
	//	or...Retrieve the host’s internet address ...
	//	InetAddress addr = InetAddress.getByName("150.203.164.3");
	//	sock = new Socket(addr, 13214);}
catch(IOException ioe) {
	System.out.println("Error opening socket: " + ioe.getMessage());
	return;
}