Socket

In this chapter you will learn:

  1. What is socket

What is socket

A socket is an endpoint of a network connection. A socket enables an application to read from and write to the network. The Socket class represents a "client" socket.

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.

Next chapter...

What you will learn in the next chapter:

  1. Create Socket from InetAddress
  2. Create a socket from IP address
  3. Create a socket with a timeout
  4. Get IP adress and port for Socket
  5. Connect to an address
Home » Java Tutorial » Socket

Socket

    Socket
    Socket creation
    Socket read
    HTTP client
    SMTP Client
    Cipher Socket
    Socket connection and thread

ServerSocket

    ServerSocket
    ServerSocket connection
    File server and client
    Thread based Server
    Time server
    SocketServer based zip server
    ServerSocketChannel
    Channel selector

SocketChannel

    SocketChannel Creation
    Read and write with SocketChannel
    SocketChannel based HTTP client
    SocketChannel Asynchronous

ServerSocketChannel

    ServerSocketChannel
    Channel selector

SSL

    SSL Client Socket
    SSL Server Socket

UDP

    DatagramSocket
    DatagramChannel
    Multicast Group

Cookie

    Cookies