Java 简明教程
Java - Socket Class with Examples
套接字使用 TCP 在两台计算机之间提供通信机制。客户端程序在其通信端创建套接字,并尝试将该套接字连接到服务器。
Sockets provide the communication mechanism between two computers using TCP. A client program creates a socket on its end of the communication and attempts to connect that socket to a server.
建立连接时,服务器在其通信端创建一个套接字对象。现在,客户端和服务器可以通过向套接字写入和从套接字读取来进行通信。
When the connection is made, the server creates a socket object on its end of the communication. The client and the server can now communicate by writing to and reading from the socket.
java.net.Socket 类表示一个套接字,而 java.net.ServerSocket 类为服务器程序提供了一种机制,用于侦听客户端并与它们建立连接。
The java.net.Socket class represents a socket, and the java.net.ServerSocket class provides a mechanism for the server program to listen for clients and establish connections with them.
建立连接后,可以使用 I/O 流进行通信。每个套接字都有一个 OutputStream 和一个 InputStream。客户端的 OutputStream 连接到服务器的 InputStream,客户端的 InputStream 连接到服务器的 OutputStream。
After the connections are established, communication can occur using I/O streams. Each socket has both an OutputStream and an InputStream. The client’s OutputStream is connected to the server’s InputStream, and the client’s InputStream is connected to the server’s OutputStream.
Java Socket 类表示客户端和服务器都用来相互通信的套接字。客户端通过实例化一个套接字对象来获取一个 Socket 对象,而服务器从 accept() 方法的返回值获取一个 Socket 对象。
The Java Socket class represents the socket that both the client and the server use to communicate with each other. The client obtains a Socket object by instantiating one, whereas the server obtains a Socket object from the return value of the accept() method.
Constructors
Sr.No. |
Method & Description |
1 |
public Socket() This method creates an unconnected socket, with the system-default type of SocketImpl. |
2 |
public Socket(String host, int port) throws UnknownHostException, IOException This method attempts to connect to the specified server at the specified port. If this constructor does not throw an exception, the connection is successful and the client is connected to the server. |
3 |
public Socket(String host,int port,InetAddress localAddr,int localPort) throws IOException This method creates a socket and connects it to the specified remote host on the specified remote port. The Socket will also bind() to the local address and port supplied. |
4 |
public Socket(InetAddress host, int port) throws IOException This method is identical to the previous constructor, except that the host is denoted by an InetAddress object. |
5 |
public Socket(InetAddress host, int port, InetAddress localAddress, int localPort) throws IOException. This method is identical to the previous constructor, except that the host is denoted by an InetAddress object instead of a String. |
6 |
public Socket(Proxy proxy) This method creates an unconnected socket, specifying the type of proxy, if any, that should be used regardless of any other settings. |
当 Socket 构造器返回时,它不仅仅实例化一个 Socket 对象,而且实际上尝试连接到指定的服务器和端口。
When the Socket constructor returns, it does not simply instantiate a Socket object but it actually attempts to connect to the specified server and port.
Methods
此处列出 Socket 类中的一些感兴趣的方法。请注意,客户端和服务器都有一个 Socket 对象,因此客户端和服务器都可以调用这些方法。
Some methods of interest in the Socket class are listed here. Notice that both the client and the server have a Socket object, so these methods can be invoked by both the client and the server.
Sr.No. |
Method & Description |
1 |
void bind(SocketAddress bindpoint) Binds the socket to a local address. |
2 |
void close() Closes this socket. |
3 |
void connect(SocketAddress endpoint) Connects this socket to the server. |
4 |
void connect(SocketAddress endpoint, int timeout) Connects this socket to the server with a specified timeout value. |
5 |
SocketChannel getChannel() Returns the unique SocketChannel object associated with this socket, if any. |
6 |
InetAddress getInetAddress() Returns the address to which the socket is connected. |
7 |
InputStream getInputStream() Returns an input stream for this socket. |
8 |
boolean getKeepAlive() Tests if SO_KEEPALIVE is enabled. |
9 |
InetAddress getLocalAddress() Gets the local address to which the socket is bound. |
10 |
int getLocalPort() Returns the local port number to which this socket is bound. |
11 |
SocketAddress getLocalSocketAddress() Returns the address of the endpoint this socket is bound to. |
12 |
boolean getOOBInline() Tests if SO_OOBINLINE is enabled. |
13 |
<T> T getOption(SocketOption<T> name) Returns the value of a socket option. |
14 |
OutputStream getOutputStream() Returns an output stream for this socket. |
15 |
int getPort() Returns the remote port number to which this socket is connected. |
16 |
int getReceiveBufferSize() Gets the value of the SO_RCVBUF option for this Socket, that is the buffer size used by the platform for input on this Socket. |
17 |
SocketAddress getRemoteSocketAddress() Returns the address of the endpoint this socket is connected to, or null if it is unconnected. |
18 |
boolean getReuseAddress() Tests if SO_REUSEADDR is enabled. |
19 |
int getSendBufferSize() Get value of the SO_SNDBUF option for this Socket, that is the buffer size used by the platform for output on this Socket. |
20 |
int getSoLinger() Returns setting for SO_LINGER. |
21 |
int getSoTimeout() Returns setting for SO_TIMEOUT. 0 returns implies that the option is disabled (i.e., timeout of infinity). |
22 |
boolean getTcpNoDelay() Tests if TCP_NODELAY is enabled. |
23 |
int getTrafficClass() Gets traffic class or type-of-service in the IP header for packets sent from this Socket |
24 |
boolean isBound() Returns the binding state of the socket. |
25 |
boolean isClosed() Returns the closed state of the socket. |
26 |
boolean isConnected() Returns the connection state of the socket. |
27 |
boolean isInputShutdown() Returns whether the read-half of the socket connection is closed. |
28 |
boolean isOutputShutdown() Returns whether the write-half of the socket connection is closed. |
29 |
void sendUrgentData(int data) Send one byte of urgent data on the socket. |
30 |
void setKeepAlive(boolean on) Enable/disable SO_KEEPALIVE. |
31 |
void setOOBInline(boolean on) Enable/disable SO_OOBINLINE (receipt of TCP urgent data) By default, this option is disabled and TCP urgent data received on a socket is silently discarded. |
32 |
<T> Socket setOption(SocketOption<T> name, T value) Sets the value of a socket option. |
33 |
void setPerformancePreferences(int connectionTime, int latency, int bandwidth) Sets performance preferences for this socket. |
34 |
void setReceiveBufferSize(int size) Sets the SO_RCVBUF option to the specified value for this Socket. |
35 |
void setReuseAddress(boolean on) Enable/disable the SO_REUSEADDR socket option. |
36 |
void setSendBufferSize(int size) Sets the SO_SNDBUF option to the specified value for this Socket. |
37 |
static void setSocketImplFactory(SocketImplFactory fac) Sets the client socket implementation factory for the application. |
38 |
void setSoLinger(boolean on, int linger) Enable/disable SO_LINGER with the specified linger time in seconds. |
39 |
void setSoTimeout(int timeout) Enable/disable SO_TIMEOUT with the specified timeout, in milliseconds. |
40 |
void setTcpNoDelay(boolean on) Enable/disable TCP_NODELAY (disable/enable Nagle’s algorithm). |
41 |
void setTrafficClass(int tc) Sets traffic class or type-of-service octet in the IP header for packets sent from this Socket. |
42 |
void shutdownInput() Places the input stream for this socket at "end of stream". |
43 |
void shutdownOutput() Disables the output stream for this socket. |
44 |
Set<SocketOption<?>> supportedOptions() Returns a set of the socket options supported by this socket. |
45 |
String toString() Converts this socket to a String. |
Socket Client Example
以下 GreetingClient 是一个客户端程序,它使用套接字连接到服务器并发送问候语,然后等待响应。
The following GreetingClient is a client program that connects to a server by using a socket and sends a greeting, and then waits for a response.
Example
package com.tutorialspoint;
import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.Socket;
public class GreetingClient {
public static void main(String [] args) {
String serverName = args[0];
int port = Integer.parseInt(args[1]);
try {
System.out.println("Connecting to " + serverName + " on port " + port);
Socket client = new Socket(serverName, port);
System.out.println("Just connected to " + client.getRemoteSocketAddress());
OutputStream outToServer = client.getOutputStream();
DataOutputStream out = new DataOutputStream(outToServer);
out.writeUTF("Hello from " + client.getLocalSocketAddress());
InputStream inFromServer = client.getInputStream();
DataInputStream in = new DataInputStream(inFromServer);
System.out.println("Server says " + in.readUTF());
client.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
以下 GreetingServer 程序是一个服务器应用程序示例,它使用 Socket 类监听命令行参数指定的端口号上的客户端—
The following GreetingServer program is an example of a server application that uses the Socket class to listen for clients on a port number specified by a command-line argument −
package com.tutorialspoint;
import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.IOException;
import java.net.ServerSocket;
import java.net.Socket;
import java.net.SocketTimeoutException;
public class GreetingServer extends Thread {
private ServerSocket serverSocket;
public GreetingServer(int port) throws IOException {
serverSocket = new ServerSocket(port);
serverSocket.setSoTimeout(10000);
}
public void run() {
while(true) {
try {
System.out.println("Waiting for client on port " +
serverSocket.getLocalPort() + "...");
Socket server = serverSocket.accept();
System.out.println("Just connected to " + server.getRemoteSocketAddress());
DataInputStream in = new DataInputStream(server.getInputStream());
System.out.println(in.readUTF());
DataOutputStream out = new DataOutputStream(server.getOutputStream());
out.writeUTF("Thank you for connecting to " + server.getLocalSocketAddress()
+ "\nGoodbye!");
server.close();
} catch (SocketTimeoutException s) {
System.out.println("Socket timed out!");
break;
} catch (IOException e) {
e.printStackTrace();
break;
}
}
}
public static void main(String [] args) {
int port = Integer.parseInt(args[0]);
try {
Thread t = new GreetingServer(port);
t.start();
} catch (IOException e) {
e.printStackTrace();
}
}
}
编译客户端和服务器,然后按以下方式启动服务器—
Compile the client and the server and then start the server as follows −
$ java GreetingServer 6066
Waiting for client on port 6066...
Just connected to /127.0.0.1:49462
Hello from /127.0.0.1:49462
Waiting for client on port 6066...
按照以下步骤检查客户端程序 −
Check the client program as follows −