Java的.net.Socket类在Java中
Java.net.Socket 类允许我们创建套接字对象,帮助我们实现所有基本的套接字操作。我们可以执行各种网络操作,例如发送、读取数据和关闭连接。使用Java.net.Socket 类创建的每个 Socket 对象都与 1 个远程主机准确关联,为了连接到另一个不同的主机,我们必须创建一个新的套接字对象。
从Java.net 包导入 Socket 类的语法:
import java.net.Socket;
Socket 类中使用的方法: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 on This 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 fac This 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 on This 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.
Socket类的应用:
1. Socket 类是在创建流套接字时实现的,它连接到指定的端口号和端口地址。
public Socket(InetAddress address, int port)
2、 socket类用于在javax.net中的指定远程端口上创建socket并连接到指定远程地址
SocketFactory.createSocket(InetAddress address, int port, InetAddress localAddress, int localPort)
3.在 javax.ssl.net 中,Socket 类用于返回一个套接字,该套接字位于在给定端口连接到命名主机的现有套接字之上。
SSLSocketFactory.createSocket(Socket s, String host, int port, boolean autoClose)
4、在javax.rmi.ssl中,Socket类用于创建SSL套接字。
SslRMIClientSocketFactory.createSocket(String host, int port)
5.在Java.nio.channels中,Socket类用于检索与其通道关联的套接字
SocketChannel.socket()
Socket 类实现的Java示例:
1.对于服务器端:
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(s.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);
}
}
}
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);
}
}
}
客户端输出:
2.对于客户端:
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);
}
}
}
服务器上的输出: