(Translated by https://www.hiragana.jp/)
java.net.ServerSocket Class in Java - GeeksforGeeks
Open In App

java.net.ServerSocket Class in Java

Last Updated : 20 Dec, 2022
Summarize
Comments
Improve
Suggest changes
Like Article
Like
Save
Share
Report
News Follow

ServerSocket Class is used for providing system-independent implementation of the server-side of a client/server Socket Connection. The constructor for ServerSocket throws an exception if it can’t listen on the specified port (for example, the port is already being used).

It is widely used so the applications of java.net.ServerSocket class which is as follows:

  1. In java.nio channel, ServerSocket class is used for retrieving a serverSocket associated with this channel.
  2. In java.rmi.Server, ServerSocket class is used to create a server socket on the specified port (port 0 indicates an anonymous port).
  3. In javax.net, Server socket is used widely so as to:
    • return an unbound server socket.
    • return a server socket bound to the specified port.
    • return a server socket bound to the specified port, and uses the specified connection backlog.
    • return a server socket bound to the specified port, with a specified listen backlog and local IP.

Let us do go through the methods of this class which is as follows:

Method Description
accept() Listens for a connection to be made to this socket and accepts it.
bind(SocketAddress endpoint) Binds the ServerSocket to a specific address (IP address and port number).
 bind(SocketAddress endpoint, int backlog) Binds the ServerSocket to a specific address (IP address and port number) and requests queqe length. If a request arrives when the queue is full then the request will be rejected by the server.
close() Closes this socket
getChannel() Returns the unique ServerSocketChannel object associated with this socket, if any.
getInetAddress() Returns the local address of this server socket.
getLocalPort() Returns the port number on which this socket is listening.
 getLocalSocketAddress() Returns the address of the endpoint this socket is bound to, or null if it is not bound yet.
getReceiveBufferSize() Gets the value of the SO_RCVBUF option for this ServerSocket, that is the proposed buffer size that will be used for Sockets accepted from this ServerSocket.
getReuseAddress() Tests if SO_REUSEADDR is enabled.
getSoTimeout() Retrieve setting for SO_TIMEOUT.
implAccept(Socket s) Subclasses of ServerSocket use this method to override accept() to return their own subclass of the socket.
 isBound() Returns the binding state of the ServerSocket.
 isClosed() Returns the closed state of the ServerSocket.
setPerformancePreferences(int connectionTime, int latency, int bandwidth) Sets performance preferences for this ServerSocket
Sets performance preferences for this ServerSocket Sets a default proposed value for the SO_RCVBUF option for sockets accepted from this ServerSocket.
setReuseAddress(boolean on) Enable/disable the SO_REUSEADDR socket option.
setSocketFactory(SocketImplFactory fac) Sets the server socket implementation factory for the application.
setSoTimeout(int timeout) Enable/disable SO_TIMEOUT with the specified timeout, in milliseconds.
toString() Returns the implementation address and implementation port of this socket as a String.

implementation:

Example 1 Server-Side

Java




// Java Program to implement ServerSocket class
// Server Side
 
// Importing required libraries
import java.io.*;
import java.net.*;
 
// Main class
public class MyServer {
 
    // Main driver method
    public static void main(String[] args)
    {
 
        // Try block to check for exceptions
        try {
 
            // Creating an object of ServerSocket class
            // in the main() method  for socket connection
            ServerSocket ss = new ServerSocket(6666);
 
            // Establishing a connection
            Socket soc = ss.accept();
 
            // Invoking input stream via getInputStream()
            // method by creating DataInputStream class
            // object
            DataInputStream dis
                = new DataInputStream(soc.getInputStream());
 
            String str = (String)dis.readUTF();
 
            // Display the string on the console
            System.out.println("message= " + str);
 
            // Lastly close the socket using standard close
            // method to release memory resources
            ss.close();
        }
 
        // Catch block to handle the exceptions
        catch (Exception e) {
 
            // Display the exception on the console
            System.out.println(e);
        }
    }
}


Output:

Example 2 Client-Side 

Java




// Java Program to implement ServerSocket class
// Client - side
 
// Importing required libraries
import java.io.*;
import java.net.*;
 
// Main class
public class MyClient {
 
    // Main driver method
    public static void main(String[] args)
    {
 
        // Try block to check if exception occurs
        try {
 
            // Creating Socket class object and
            // initializing Socket
            Socket soc = new Socket("localhost", 6666);
 
            DataOutputStream d = new DataOutputStream(
                soc.getOutputStream());
 
            // Message to be displayed
            d.writeUTF("Hello GFG Readers!");
 
            // Flushing out internal buffers,
            // optimizing for better performance
            d.flush();
 
            // Closing the connections
 
            // Closing DataOutputStream
            d.close();
            // Closing socket
            soc.close();
        }
 
        // Catch block to handle exceptions
        catch (Exception e) {
 
            // Print the exception on the console
            System.out.println(e);
        }
    }
}


Output:

 



Previous Article
Next Article

Similar Reads

java.net.URLConnection Class in Java
URLConnection Class in Java is an abstract class that represents a connection of a resource as specified by the corresponding URL. It is imported by the java.net package. The URLConnection class is utilized for serving two different yet related purposes, Firstly it provides control on interaction with a server(especially an HTTP server) than URL cl
5 min read
java.net.SecureCacheResponse Class in Java
The SecureCacheResponse Class in Java represents a cache response originally retrieved through secure means. Syntax: Class Declaration public abstract class SecureCacheResponse extends CacheResponse The constructor for this class is as follows SecureCacheResponse() Now, the methods of this class are as follows: MethodDescriptiongetCipherSuite()This
3 min read
java.net.CookieManager Class in Java
The CookieManager class provides a precise implementation of CookieHandler. This separates the storage of cookies from the policy surrounding accepting and rejecting cookies. A CookieManager is initialized with a CookieStore and a CookiePolicy. The CookieStore manages storage, and the CookiePolicy object makes policy decisions on cookie acceptance/
4 min read
java.net.CacheResponse Class in Java
CacheResponse is an abstract class that represents channels for retrieving resources from the ResponseCache. The objects of this class provide an InputStream that returns the entity-body and the associated response headers. This class inherits methods from java.lang.Object like as clone, equals, finalize, getClass(), hashCode(), notify(), notifyAll
3 min read
java.net.CacheRequest Class in Java
CacheRequest class is used in java whenever there is a need for, storage of resources in ResponseCache. More precisely instances of this class provide an advantage for the OutputStream object to store resource data into the cache, in fact, This OutputStream object is invoked by protocol handlers. CacheRequest class belongs to java.net package along
3 min read
java.net.CookieHandler Class in Java
The object of the CookieHandler Class in Java provides a callback mechanism for hooking up an HTTP state management policy implementation into the HTTP protocol handler. The mechanism of how to make HTTP requests and responses is specified by the HTTP state management mechanism. A system-wide CookieHandler that too employed by the HTTP protocol han
2 min read
java.net.SocketPermission Class in Java
The java.net.SocketPermisson class represents whether you have permission to access a network via sockets. A SocketPermission consists of a host and a set of actions. Class Declaration: public final class SocketPermission extends Permission implements SerializableConstructor: ConstructorDescriptionManagementPermission(String name)This constructs a
2 min read
java.net.PasswordAuthentication Class in Java
PasswordAuthentication class is provided by package java.net for implementing networking applications, and it is used in those cases when it is required to hold the data that will be used by the Authenticator. It holds the username and password. Syntax of its constructors : PasswordAuthentication(String userName, char[] password)This will create ne
2 min read
java.net.URL Class in Java
URL is an acronym of Uniform resource locator. It is a pointer to locate resource in www (World Wide Web). A resource can be anything from a simple text file to any other like images, file directory etc. The typical URL may look like http://www.example.com:80/index.htmlThe URL has the following parts: Protocol: In this case the protocol is HTTP, It
4 min read
java.net.URLPermission Class in Java
URLPermission class is used to represent the permission to access the resources of the given URL. The given URL acts as the name of the permission. The actions represent the request methods and headers. Class declaration: public final class URLPermission extends PermissionConstructors: ConstructorDescriptionURLPermission(String url) This constructo
2 min read
java.net.InetAddress Class in Java
public class InetAddress extends Object implements Serializable: The java.net.InetAddress class provides methods to get the IP address of any hostname. An IP address is represented by 32-bit or 128-bit unsigned number. InetAddress can handle both IPv4 and IPv6 addresses. There are 2 types of addresses : Unicast — An identifier for a single interfac
6 min read
java.net.Socket Class in Java
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
5 min read
java.net.ResponseCache Class in Java
ResponseCache in java is used for constructing implementation of URLConnection caches, and it nominates which resource has to be cached and up to what time duration a resource needed to be cached. An instance of ResponseCache can be created using the system by doing : ResponseCache.setDefault(ResponseCache) The instance created by using the above s
3 min read
java.net.NetPermission Class in Java
NetPermission class is used to allow network permissions. NetPermission class extends BasicPermission class. It is a “named” permission i.e it contains a name but no action. Permission nameWhat permission allowsRisks associated with this permissionallowHttpTraceThis permission allows using the HTTP TRACE method in HttpURLConnectionAttackers may use
5 min read
java.net.Proxy Class in Java
A proxy is an immutable object and type of tool or application or program or system, which helps to protect the information of its users and computers. It acts as a barrier between computer and internet users. A Proxy Object defines the Proxy settings to be used with a connection. Proxy servers are already pre-installed in Windows in a type of prog
3 min read
java.net.ProxySelector Class in Java
ProxySelector determines which resource has to be requested via proxy as a result return List<Proxy> Methods of ProxySelector class : MethodDescriptionconnectFailed()This method is invoked when failed to establish a connectiongetDefault()This method is used for retrieving the system-wide ProxySelectorselect()This method returns Proxy to acces
3 min read
java.net.CookieStore Class in Java
A CookieStore is an interface in Java that is a storage area for cookies. It is used to store and retrieve cookies. A CookieStore is responsible for removing HTTPCookie instances that have expired. The CookieManager adds the cookies to the CookieStore for every incoming HTTP response by calling CookieStore.add() and retrieves the cookies from the C
4 min read
java.net.ProtocolFamily Class in Java
ProtocolFamily is a java Interface. The java.net.ProtocolFamily represents a family of communication protocols. Java.net.StandardProtocolFamily implements ProtocolFamily Interface. public interface ProtocolFamily Methods of java.net.ProtocolFamily java.net.ProtocolFamily interface contains only one method: S.No. Method Description Return Type 1.nam
2 min read
java.net.CookiePolicy Class in Java
CookiePolicy implementations decide which cookies should be accepted and which should be rejected. Three pre-defined policy implementations are provided, namely ACCEPT_ALL, ACCEPT_NONE, and ACCEPT_ORIGINAL_SERVER. Signaturepublic interface CookiePolicyFields S.NO Field Description Data Type 1.ACCEPT_ALL CookiePolicy.ACCEPT_ALL is a predefined polic
2 min read
java.net.SocketOption Class in Java
The java.net.SocketOption is a socket option that is connected with a socket, as the set of channels packages is java.nio.channels.NetworkChannel that this interface has defined the setOption as well as the getOption methods to set and query's the channels within its Socket Options. --> java.net Package --> SocketOption Class This java.net.So
4 min read
java.net.SocketImplFactory Class in Java
In Java, SocketImplFactory Class is an interface java.net.SocketImplFactory Class is defining a factory for SocketImpl instances, as this interface is usable by sockets classes to create the sockets execution that implements various policies through it. Interface java.net.SocketImplFactory Class is defining the factory for setting the socketing exe
2 min read
Java.net.HttpURLConnection Class in Java
HttpURLConnection class is an abstract class directly extending from URLConnection class. It includes all the functionality of its parent class with additional HTTP-specific features. HttpsURLConnection is another class that is used for the more secured HTTPS protocol. It is one of the popular choices among Java developers for interacting with web
5 min read
Java.net.JarURLConnection class in Java
Prerequisite - JAR files in Java What is a Jar file? JavaArchive(JAR) bundles all the classes in one package. Since the archive is compressed and can be downloaded in a single HTTP connection, it is often faster to download the archive than to download individual classes. Although jar bundles all the classes, their fully classified names can be use
4 min read
java.net.BindException in Java with Examples
The java.net.BindException is an exception that is thrown when there is an error caused in binding when an application tries to bind a socket to a local address and port. Mostly, this may occur due to 2 reasons, either the port is already in use(due to another application) or the address requested just cannot be assigned to this application. The Bi
2 min read
How to Fix java.net.ConnectException: Connection refused: connect in Java?
java.net.ConnectException: Connection refused: connect is the most frequent kind of occurring networking exception in Java whenever the software is in client-server architecture and trying to make a TCP connection from the client to the server. We need to handle the exception carefully in order to fulfill the communication problem. First, let us se
4 min read
java.net.SocketException in Java with Examples
SocketException is a subclass of IOException so it's a checked exception. It is the most general exception that signals a problem when trying to open or access a socket. The full exception hierarchy of this error is: java.lang.Object java.lang.Throwable java.lang.Exception java.io.IOException java.net.SocketException As you might already know, it's
5 min read
java.net.FileNameMap Interface in Java
java.net.FileNameMap is a Java Interface. FileNameMap interface is a part of the java.net package. FileNameMap provides a mechanism to map between a file name and a MIME type string. We can use FileNameMap getContentTypeFor method to get the MIME type of the specified file. Syntax: public interface FileNameMapMethod of java.net.FileNameMap Interfac
2 min read
Java.lang.Class class in Java | Set 1
Java provides a class with name Class in java.lang package. Instances of the class Class represent classes and interfaces in a running Java application. The primitive Java types (boolean, byte, char, short, int, long, float, and double), and the keyword void are also represented as Class objects. It has no public constructor. Class objects are cons
15+ min read
Java.lang.Class class in Java | Set 2
Java.lang.Class class in Java | Set 1 More methods: 1. int getModifiers() : This method returns the Java language modifiers for this class or interface, encoded in an integer. The modifiers consist of the Java Virtual Machine's constants for public, protected, private, final, static, abstract and interface. These modifiers are already decoded in Mo
15+ min read
HTTP API of java.net.http Package With Examples
HTTP Client and WebSocket APIs provide high-level client interfaces to HTTP (versions 1.1 and 2) and low-level client interfaces to WebSocket. The main types defined are namely as follows: HttpClientHttpRequestHttpResponse The protocol-specific requirements are defined in the Hypertext Transfer Protocol Version 2 (HTTP/2), the Hypertext Transfer Pr
14 min read
Article Tags :
Practice Tags :