Java Reference
In-Depth Information
Contacting a Server
Problem
You need to contact a server using TCP/IP.
Solution
Just create a java.net.Socket , passing the hostname and port number into the constructor.
Discussion
There isn't much to this in Java. When creating a socket, you pass in the hostname and the
port number. The java.net.Socket constructor does the gethostbyname() and the sock-
et() system call, sets up the server's sockaddr_in structure, and executes the connect()
call. All you have to do is catch the errors, which are subclassed from the familiar IOExcep-
tion . Example 13-2 sets up a Java network client, but doesn't actually do any I/O yet. It uses
try-with-resources (see Try With Resources ) to ensure that the socket is closed automatically
when we are done with it.
Example 13-2. network/ConnectSimple.java (simple client connection)
import
import java.net.Socket
java.net.Socket ;
/* Client with NO error handling */
public
public class
class ConnectSimple
ConnectSimple {
public
public static
static void
void main ( String [] argv ) throws
throws Exception {
try
try ( Socket sock = new
new Socket ( "localhost" , 8080 )) {
/* If we get here, we can read and write on the socket "sock" */
System . out . println ( " *** Connected OK ***" );
/* Do some I/O here... */
}
}
}
Search WWH ::




Custom Search