Skip to main content Skip to docs navigation
TechSpiderTutorials

java.net.Socket Class - Java Networking API

java.net.Socket

This class implements client sockets (also called just "sockets"). A socket is an endpoint for communication between two machines.

The actual work of the socket is performed by an instance of the SocketImpl class. An application, by changing the socket factory that creates the socket implementation, can configure itself to create sockets appropriate to the local firewall.

Creating Objects

1. For connecting to a server:

Socket(String host, int port)

String host = "example.com";
int port = 80;
Socket socket = new Socket(host, port);
2. For binding to a specific local address and port::

Socket(InetAddress address, int port)

InetAddress address = InetAddress.getLocalHost();
int port = 8080;
Socket socket = new Socket(address, port);
3. For creating a socket and connecting it to another socket:

Socket(InetAddress address, int port, InetAddress localAddr, int localPort)

InetAddress remoteAddress = InetAddress.getByName("example.com");
int remotePort = 80;
InetAddress localAddress = InetAddress.getLocalHost();
int localPort = 0; // 0 means let the system choose a free port
Socket socket = new Socket(remoteAddress, remotePort, localAddress, localPort);

java.net.SocketMethods

public void bind(SocketAddress bindpoint)

Binds the socket to a local address.


public void close()

Closes this socket.


public void connect(SocketAddress endpoint)

Connects this socket to the server.


public void connect(SocketAddress endpoint, int timeout)

Connects this socket to the server with a specified timeout value.


public SocketChannel getChannel()

Returns the unique SocketChannel object associated with this socket, if any.


public InetAddress getInetAddress()

Returns the address to which the socket is connected.


public InputStream getInputStream()

Returns an input stream for this socket.


public boolean getKeepAlive()

Tests if SO_KEEPALIVE is enabled.


public InetAddress getLocalAddress()

Gets the local address to which the socket is bound.


public int getLocalPort()

Returns the local port number to which this socket is bound.


public SocketAddress getLocalSocketAddress()

Returns the address of the endpoint this socket is bound to.


public OutputStream getOutputStream()

Returns an output stream for this socket.


public int getPort()

Returns the remote port number to which this socket is connected.


public int getReceiveBufferSize()

Gets the value of the SO_RCVBUF option for this Socket, that is the buffer size used by the platform for input on this Socket.


public SocketAddress getRemoteSocketAddress()

Returns the address of the endpoint this socket is connected to, or null if it is unconnected.


public boolean isBound()

Returns the binding state of the socket.


public boolean isClosed()

Returns the closed state of the socket.


public boolean isConnected()

Returns the connection state of the socket.


public boolean isInputShutdown()

Returns whether the read-half of the socket connection is closed.


public boolean isOutputShutdown()

Returns whether the write-half of the socket connection is closed.


public void sendUrgentData(int data)

Send one byte of urgent data on the socket.


public void setKeepAlive(boolean on)

Enable/disable SO_KEEPALIVE.


public void setOOBInline(boolean on)

Enable/disable SO_OOBINLINE (receipt of TCP urgent data) By default, this option is disabled and TCP urgent data received on a socket is silently discarded.


public void setPerformancePreferences(int connectionTime, int latency, int bandwidth)

Sets performance preferences for this socket.


public void setReceiveBufferSize(int size)

Sets the SO_RCVBUF option to the specified value for this Socket.


public void setReuseAddress(boolean on)

Enable/disable the SO_REUSEADDR socket option.


public void setSendBufferSize(int size)

Sets the SO_SNDBUF option to the specified value for this Socket.


public static void setSocketImplFactory(SocketImplFactory fac)

Sets the client socket implementation factory for the application.


public void setSoLinger(boolean on, int linger)

Enable/disable SO_LINGER with the specified linger time in seconds.


public void setSoTimeout(int timeout)

Enable/disable SO_TIMEOUT with the specified timeout, in milliseconds.


public void setTcpNoDelay(boolean on)

Enable/disable TCP_NODELAY (disable/enable Nagle's algorithm).


public void setTrafficClass(int tc)

Sets traffic class or type-of-service octet in the IP header for packets sent from this Socket.


public void shutdownInput()

Places the input stream for this socket at "end of stream".


public void shutdownOutput()

Disables the output stream for this socket.


public String toString()

Converts this socket to a String


java.net.Socket Class Example

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.io.PrintWriter;
import java.net.Socket;
import java.net.UnknownHostException;

public class SocketExample {
    public static void main(String[] args) {
        String serverAddress = "127.0.0.1"; // Server's IP address
        int port = 12345; // Port number the server is listening on
        
        try {
            // Create a socket to connect to the server
            Socket socket = new Socket(serverAddress, port);
            
            // Setup streams for sending and receiving data
            PrintWriter out = new PrintWriter(new OutputStreamWriter(socket.getOutputStream()), true);
            BufferedReader in = new BufferedReader(new InputStreamReader(socket.getInputStream()));
            
            // Send a message to the server
            String messageToSend = "Hello, Server!";
            out.println(messageToSend);
            System.out.println("Sent to server: " + messageToSend);
            
            // Receive a message from the server
            String receivedMessage = in.readLine();
            System.out.println("Received from server: " + receivedMessage);
            
            // Close resources
            out.close();
            in.close();
            socket.close();
            
        } catch (UnknownHostException e) {
            System.err.println("Unknown host: " + serverAddress);
            e.printStackTrace();
        } catch (IOException e) {
            System.err.println("IOException while communicating with the server");
            e.printStackTrace();
        }
    }
}