GV

GeezerVison

The World Wide Web, restored to 800 pixels of glory.

Home|About|Gaming cabinet|Archives|How it works|Starter sites

On this site

  • Java Tutorial
  • Advanced Java
  • Interview Questions
  • Exercises
  • Examples
  • Quizzes
  • Projects
  • Cheatsheet
  • DSA in Java
  • Java Collection
  • Introduction3 min read
  • Variables2 min read
  • Data Types7 min read
  • Operators7 min read

This view

  • Original page
  • New address

GeezerVison is showing www.geeksforgeeks.org — java.net.Socket Class in Java - GeeksforGeeks

geeksforgeeks
search icon
  • Courses
  • Tutorials
  • Interview Prep
  • Java Tutorial
  • Advanced Java
  • Interview Questions
  • Exercises
  • Examples
  • Quizzes
  • Projects
  • Cheatsheet
  • DSA in Java
  • Java Collection

java.net.Socket Class in Java

Last Updated : 19 Oct, 2022

The java.net.Socket class allows us to create socket objects that help us in implementing all fundamental socket operations. We can perform various networking operations such as sending, reading data and closing connections. Each Socket object that has been created using with java.net.Socket class has been associated exactly with 1 remote host, for connecting to another different host, we must create a new socket object.

The syntax for importing Socket class from java.net package :

import java.net.Socket;

 Methods used in Socket class : 

Method Description
bind(SocketAddress bindpoint)This method is used for binding a socket to a local address.
Close()This method is used for terminating a socket.
connect(SocketAddress endpoint)This method is used in connecting a socket to the server.
getChannel()This method returns out the object which is associated with the socket if any.
getInetAddress()This method returns the Address to which the socket is connected to.
getInputStream()This method returns the input stream for the socket.
getKeepAlive()This method is used to check if SO_KEEPALIVE is enabled or not.
getLocalAddress()This method is used to fetch the local address to which the socket is bound.
getLocalPort()This method returns the local address to which the socket is bound to.
getLocalSocketAddress()This method returns the endpoint for which the socket is bound.
getOOBInline()This method checks if SO_OOBINLINE is enabled.
getOutputStream()This method returns the output stream for the socket.
getPort()This method returns the remote port number with which the socket is associated to.
 getReceiveBufferSize()This method is used to fetch the value of SO_RCVBUF option for the socket, which is a buffer size used as input by the platform on the socket.
getRemoteSocketAddress()This method returns, address of the endpoint for the socket or if it's not connected then it returns null.
getReuseAddress()This method checks if REUSE_ADDR is enabled.
getSendBufferSize()This method is used to get the value of SO_SNDBUF option of the socket which is used as a buffer size for output by the platform on the socket.
 getSoLinger()This method returns the setting for SO_LINGER
getSoTimeout()This method returns the setting for S0_TIMEOUT
getTcpNoDelay()This method is used for testing if TCP_NODELAY is enabled or not.
getTrafficClass()This method gets traffic class or type-of-service in the IP header for packets sent from this Socket.
isBound()This method returns the binding state of the socket
isClosed()This method returns the closed state of the socket.
isConnected()This method returns the connection state of the socket.
isInputShutdown()This method returns whether the read-half of the socket connection is closed
isOutputShutdown()This method returns whether the write-half of the socket connection is closed.
sendUrgentData(int data)This method sends one byte of urgent data on the socket
setKeepAlive(boolean on)This method enables/disables SO_KEEPALIVE
setOOBInline(boolean on)This Method enables/disables SO_OOBINLINE (a receipt of TCP urgent data) By default, this option is disabled, and TCP urgent data received on a socket is silently discarded.
setPerformancePreferences(int connectionTime, int latency, int bandwidth)This method sets performance preferences for this socket.
 setReceiveBufferSize(int size)This method sets the SO_RCVBUF option to the specified value for this Socket.
 setReuseAddress(boolean onThis method enables/disables the SO_REUSEADDR socket option
setSendBufferSize(int size)This method sets the SO_SNDBUF option to the specified value for this Socket
setSocketImplFactory(SocketImplFactory facThis method sets the client socket implementation factory for the application.
setSoLinger(boolean on, int linger)This method enables/disables SO_LINGER with the specified linger time in seconds.
setSoTimeout(int timeout)This method enables/disables SO_TIMEOUT with the specified timeout, in milliseconds.
 setTcpNoDelay(boolean onThis method enables/disables TCP_NODELAY (disable/enable Nagle's algorithm).
setTrafficClass(int tc)This method sets traffic class or type-of-service octet in the IP header for packets sent from this Socket.
 shutdownInput()This method places the input stream for this socket at the "end of stream".
 toString()This method converts the Socket to a string.

Applications of Socket Class:

1. Socket class is implemented in creating a stream socket and which is connected to a specified port number and port address.

public Socket(InetAddress address, int port)

2. Socket class is used for the creation of socket and connecting to the specified remote address on the specified remote port in javax.net

    SocketFactory.createSocket(InetAddress address, int port, InetAddress localAddress, int localPort)

3. In javax.ssl.net, the Socket class is used to return a socket layered over an existing socket connected to the named host at a given port.

SSLSocketFactory.createSocket(Socket s, String host, int port, boolean autoClose)

4. In javax.rmi.ssl, Socket class is used for creating an SSL socket.

SslRMIClientSocketFactory.createSocket(String host, int port)

5. In java.nio.channels, Socket class is used for retrieving a socket associated with its channel

SocketChannel.socket()

Java Example for Socket class Implementation :

1. For Server Side:

Java
import java.io.*;
import java.net.*;
public class MyServer {
    public static void main(String[] args)
    {
        try {
            ServerSocket ss = new ServerSocket(6666);
          
            // establishes connection
            Socket soc = ss.accept();
          
            // invoking input stream
            DataInputStream dis = new DataInputStream(ss.getInputStream());
          
            String str = (String)dis.readUTF();
          
            System.out.println("message= " + str);
          
            // closing socket
            ss.close();
          
        } // for catching Exception in run time
        catch (Exception e) {
            System.out.println(e);
        }
    }
}

Output on Client :

2. For Client Side :

Java
import java.io.*;
import java.net.*;
public class MyClient {
    public static void main(String[] args)
    {
        try {
          
            // initializing Socket
            Socket soc = new Socket("localhost", 6666);
          
            DataOutputStream d = new DataOutputStream(
                soc.getOutputStream());
          
            // message to display
            d.writeUTF("Hello GFG Readers!");         
       
            d.flush();
          
            // closing DataOutputStream
            d.close();
          
            // closing socket
            soc.close();
        }
      
        // to initialize Exception in run time
        catch (Exception e) {
            System.out.println(e);
        }
    }
}

Output on server :

Comment

Explore

    Basics
    • Introduction3 min read
    • Variables2 min read
    • Data Types7 min read
    • Operators7 min read
    • Decision Making5 min read
    • Methods7 min read
    • Arrays7 min read
    • Strings5 min read
    OOP & Interface
    • Introduction6 min read
    • Constructors6 min read
    • Encapsulation3 min read
    • Inheritance8 min read
    • Polymorphism5 min read
    • Abstraction5 min read
    • Interfaces8 min read
    Collections
    • Collection class9 min read
    • Collection Interface5 min read
    • List Interface8 min read
    • Set Interface5 min read
    • Queue Interface5 min read
    • Map Interface in Java6 min read
    • Iterator4 min read
    Advance Java Concepts
    • Exception handling6 min read
    • Java Multithreading Tutorial3 min read
    • Synchronization in Java9 min read
    • File handling6 min read
    • Method References3 min read
    • Java 8 Stream Tutorial7 min read
    • Memory Management4 min read
    • Garbage Collection in Java6 min read
    • Networking6 min read
    • JDBC5 min read
    Practice Java
    • Interview Questions15+ min read
    • Programs6 min read
    • Practice Problems5 min read
    • Quiz1 min read
    • Project Ideas15+ min read
    Courses
    • Java Backend Course2 min read
    • Placement 360 Course2 min read
You are visitor 01402503 — GeezerVison does not store the pages you look up.
Best viewed with Netscape Navigator 4.7 or Internet Explorer 6 at 800×600. No cookies required.