Java实现 服务端起10个线程ID监听40-49这10个端口,这10个端口注册到注册中心,提供同一个服务,发个A,响应B,客户端起10个线程去注册中心请求
好的,我们可以通过实现一个简单的服务端、注册中心和客户端来达到这个目的。以下是详细的代码示例:
服务端代码
java
import java.io.*;
import java.net.*;
import java.util.concurrent.*;
public class MultiPortServer {
private static final int PORT_START = 40;
private static final int PORT_END = 49;
private static final ExecutorService executor = Executors.newFixedThreadPool(PORT_END - PORT_START + 1);
public static void main(String[] args) {
for (int port = PORT_START; port <= PORT_END; port++) {
int finalPort = port;
executor.submit(() -> startServer(finalPort));
RegistryCenter.registerService(finalPort, "localhost");
}
}
private static void startServer(int port) {
try (ServerSocket serverSocket = new ServerSocket(port)) {
System.out.println("Server listening on port " + port);
while (true) {
Socket clientSocket = serverSocket.accept();
handleClient(clientSocket);
}
} catch (IOException e) {
e.printStackTrace();
}
}
private static void handleClient(Socket clientSocket) {
try (BufferedReader in = new BufferedReader(new InputStreamReader(clientSocket.getInputStream()));
PrintWriter out = new PrintWriter(clientSocket.getOutputStream(), true)) {
String message = in.readLine();
if ("A".equals(message)) {
out.println("B");
} else {
out.println("Unknown message");
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
注册中心代码
java
import java.util.*;
import java.util.concurrent.*;
public class RegistryCenter {
private static final Map<Integer, String> serviceRegistry = new ConcurrentHashMap<>();
public static void registerService(int port, String address) {
serviceRegistry.put(port, address);
System.out.println("Service registered on port " + port + " at address " + address);
}
public static String lookupService(int port) {
return serviceRegistry.get(port);
}
public static List<Integer> getAllServicePorts() {
return new ArrayList<>(serviceRegistry.keySet());
}
}
客户端代码
java
import java.io.*;
import java.net.*;
import java.util.List;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
public class Client {
private static final int CLIENT_COUNT = 10;
private static final ExecutorService executor = Executors.newFixedThreadPool(CLIENT_COUNT);
public static void main(String[] args) {
List<Integer> servicePorts = RegistryCenter.getAllServicePorts();
for (int i = 0; i < CLIENT_COUNT; i++) {
executor.submit(() -> {
int portIndex = (int) (Math.random() * servicePorts.size());
int servicePort = servicePorts.get(portIndex);
queryService(servicePort);
});
}
executor.shutdown();
}
private static void queryService(int servicePort) {
String serviceAddress = RegistryCenter.lookupService(servicePort);
if (serviceAddress != null) {
try (Socket socket = new Socket(serviceAddress, servicePort);
PrintWriter out = new PrintWriter(socket.getOutputStream(), true);
BufferedReader in = new BufferedReader(new InputStreamReader(socket.getInputStream()))) {
out.println("A");
String response = in.readLine();
System.out.println("Response from server on port " + servicePort + ": " + response);
} catch (IOException e) {
e.printStackTrace();
}
} else {
System.out.println("No service found on port " + servicePort);
}
}
}
运行步骤
-
启动服务端:
- 运行
MultiPortServer
类。它将启动10个线程,每个线程监听一个端口(40-49),并将这些服务注册到注册中心。
- 运行
-
启动客户端:
- 运行
Client
类。它将启动10个客户端线程,每个线程随机选择一个服务端口,从注册中心获取该端口的服务地址,并发送消息 "A"。
- 运行
说明
-
服务端:
MultiPortServer
类创建一个线程池,每个线程监听一个特定端口,并将该端口的服务注册到RegistryCenter
。- 每个服务端口接收到消息 "A" 后,响应消息 "B"。
-
注册中心:
RegistryCenter
类负责管理服务的注册和查询。- 提供了
registerService
方法用于注册服务,lookupService
方法用于查询服务地址,getAllServicePorts
方法用于获取所有注册的服务端口。
-
客户端:
Client
类创建一个线程池,启动10个客户端线程,每个线程随机选择一个服务端口,向服务端发送消息 "A",并打印服务端的响应。