Mega Code Archive

 
Categories / Java Book / 006 Networking
 

0367 Socket

ServerSocket is for servers. The Socket class is for clients. Here are two constructors used to create client sockets: Socket(String hostName, int port) throws UnknownHostException, IOException Creates a socket connected to the named host and port. Socket(InetAddress ipAddress, int port) throws IOException Creates a socket using a preexisting InetAddress object and a port. Methods from Socket InetAddress getInetAddress( ) Returns the InetAddress associated with the Socket object. It returns null if the socket is not connected. int getPort( ) Returns the remote port to which the invoking Socket object is connected. It returns 0 if the socket is not connected. int getLocalPort( ) Returns the local port to which the invoking Socket object is bound. It returns -1 if the socket is not bound. InputStream getInputStream( ) throws IOException Returns the InputStream associated with the invoking socket. OutputStream getOutputStream( ) throws IOException Returns the OutputStream associated with the invoking socket. connect( ) allows you to specify a new connection; isConnected( ) returns true if the socket is connected to a server; isBound( ) returns true if the socket is bound to an address; isClosed( ) returns true if the socket is closed.