ServerSocket Class in Java provides a system-independent way to implement 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).
- In the java.nio channel, ServerSocket class is used for retrieving a ServerSocket associated with this channel.
- In java.rmi.Server, ServerSocket class is used to create a server socket on the specified port (port 0 indicates an anonymous port).
- In javax.net, the ServerSocket is used widely 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.
Server-Side Programming
The below Java program demonstrates the working of server-side programming using ServerSocket class.
Java
// Java program demonstrates the
// working of server-side programming
// using ServerSocket class
import java.io.*;
import java.net.*;
import java.io.*;
import java.net.*;
public class MyServer {
public static void main(String[] args) {
try {
System.out.println("Starting server...");
// Create a ServerSocket listening on port 6666
ServerSocket ss = new ServerSocket(6666);
System.out.println("Server started. Listening on port 6666...");
// Accept a connection from a client
Socket s = ss.accept();
System.out.println("Client connected!");
// Read the message from the client
DataInputStream d = new DataInputStream(s.getInputStream());
String str = d.readUTF();
System.out.println("Message: " + str);
// Close the socket
ss.close();
} catch (Exception e) {
System.out.println("Server Error: " + e);
}
}
}
Output:
Explanation: In the above example, it demonstrates a basic server-side implementation using the ServerSocket class. It listens on port 6666, accepts a client connection, reads a message sent by the client, and then closes the connection.
Client-Side Programming
The below Java program demonstrate the working of client-side programming using ServerSocket class.
Java
// Java program demonstrates the
// working of client-side programming
// using ServerSocket class
import java.io.*;
import java.net.*;
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 s = new Socket("localhost", 6666);
DataOutputStream d = new DataOutputStream(
s.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
s.close();
}
// Catch block to handle exceptions
catch (Exception e) {
// Print the exception on the console
System.out.println(e);
}
}
}
Output:
Explanation: In the above example, it demonstrates a basic client-side implementation using the Socket class. It connects to a server at localhost on port 6666, sends a message "Hello GFG Readers!", and then closes the connection.
Methods of Java ServerSocket
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. |
Similar Reads
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 h
5 min read
Java Observable Class In Java, the Observable class is used to create objects that can be observed by other parts of the program. When an object of such a subclass undergoes a change, observing classes are notified. The update() method is called when an observer is notified of a change. Note: The Observable class and Obs
8 min read
Java Reader Class Reader class in Java is an abstract class used for reading character streams. It serves as the base class for various subclasses like FileReader, BufferedReader, CharArrayReader, and others, which provide more efficient implementations of the read() method. To work with the Reader class, we must ext
6 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
5 min read
Object Class in Java Object class in Java is present in java.lang package. Every class in Java is directly or indirectly derived from the Object class. If a class does not extend any other class then it is a direct child class of the Java Object class and if it extends another class then it is indirectly derived. The Ob
7 min read
Java Cheat Sheet Java is a programming language and platform that has been widely used since its development by James Gosling in 1991. It follows the Object-oriented Programming concept and can run programs written on any OS platform. Java is a high-level, object-oriented, secure, robust, platform-independent, multi
15+ min read