Java的.net.ServerSocket类在Java中
ServerSocket 类用于提供客户端/服务器套接字连接的服务器端的独立于系统的实现。如果 ServerSocket 的构造函数无法侦听指定的端口(例如,该端口已被使用),则会引发异常。
它被广泛使用,所以Java.net.ServerSocket 类的应用如下:
- 在Java.nio 通道中,ServerSocket 类用于检索与此通道关联的 serverSocket。
- 在Java.rmi.Server 中,ServerSocket 类用于在指定端口(端口 0 表示匿名端口)上创建服务器套接字。
- 在 javax.net 中,Server socket 被广泛使用,以便:
- 返回一个未绑定的服务器套接字。
- 返回绑定到指定端口的服务器套接字。
- 返回绑定到指定端口的服务器套接字,并使用指定的连接积压。
- 返回绑定到指定端口的服务器套接字,具有指定的侦听积压和本地 IP。
让我们来看看这个类的方法,如下所示: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). 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.
执行:
示例 1服务器端
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(s.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);
}
}
}
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);
}
}
}
输出:
示例 2客户端
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);
}
}
}
输出: