Client Socket

The Socket class abstracts the performance of a TCP/IP connection through which a client and a server can communicate. Instances of the Socket class initiate the connection to a server program, send the requests to the server machine, and wait for and handle the reply.

The Socket object should specify the host name ( either IP address or DNS name ) and the port number on the host through which to communicate. Once communication with the server is established, standard streams may be acquired through the Socket class to pass information back and forth. For initial testing of client/server interaction, use the loopback IP address 127.0.0.1

As a helper class for sockets and datagram connections, the InetAddress class represents an Internet address, and has a static getByName() method that takes a hostname as argument and returns an InetAddress object (IP address).

Here's a Client socket example:


import java.net.*;
import java.io.*;

public class ClientTest {

	public static void main (String args[]) {
		String data;
		try {
			Socket s = new Socket("127.0.0.1", 6000);
			InputStream in = s.getInputStream();
			BufferedReader buf = new BufferedReader( new 
                        InputStreamReader(in));
			System.out.println(buf.readLine());
			buf.close();
			s.close();
		}
		catch (Exception e) 
			{ System.out.println("Exception: " + e); }
	}
}

 

Next...                                                                                                                                page 11-7