关于Socket的官方文档。java.net.Socket
https://docs.oracle.com/javase/8/docs/api/
package ClientAndServer;
import java.net.InetAddress;
import java.net.Socket;
public class Client {
public static void main(String[] args) throws Exception{
final int length = 100;
String host = "localhost";
int port = 1122;
Socket[] sockets = new Socket[length];
for(int i = 0;i<length;i++){
sockets[i] = new Socket(InetAddress.getByName(host),port);//Creates a stream socket and connects it to the specified port number at the specified IP address.
System.out.println("第"+(i+1)+"次连接成功");
}
Thread.sleep(3000);
for(int i = 0;i<length;i++){
sockets[i].close();
}
}
}
关于ServerSocket的官方文档
public class ServerSocket extends Object implements Closeable
This class implements server sockets. A server socket waits for requests to come in over the network. It performs some operation based on that request, and then possibly returns a result to the requester.
The actual work of the server socket is performed by an instance of the SocketImpl
class. An application can change the socket factory that creates the socket implementation to configure itself to create sockets appropriate to the local firewall.
Since:
JDK1.0
ServerSocket() Creates an unbound server socket. |
ServerSocket(int port) Creates a server socket, bound to the specified port. |
ServerSocket(int port, int backlog) Creates a server socket and binds it to the specified local port number, with the specified backlog. |
ServerSocket(int port, int backlog, InetAddress bindAddr) Create a server with the specified port, listen backlog, and local IP address to bind to.
|
关于ServerSocket的accept()方法
Socket | accept() Listens for a connection to be made to this socket and accepts it. |
服务器等待客户端连接正在监听的窗口
package ClientAndServer;
import java.io.IOException;
import java.net.ServerSocket;
import java.net.Socket;
public class Server {
private int port = 1122;
private ServerSocket serverSocket;
public Server() throws Exception{
serverSocket = new ServerSocket(port,3);
}
public void service(){
while(true){
Socket socket = null;
try{
socket = serverSocket.accept();//等待客户端连接正在监听的窗口
System.out.println("New Connection Accept!");
}catch(IOException e){
e.printStackTrace();
}finally{
if(socket != null){
try{
socket.close();
}catch(IOException e){
e.printStackTrace();
}
}
}
}
}
public static void main(String[] args) throws Exception{
Server server = new Server();
Thread.sleep(60000*10);
server.service();
}
}