Java MQ(Message Queue)是消息隊列的一種實現方式,它可以在分布式系統中傳遞消息,實現系統之間異步解耦。Java MQ中使用消息代理(Broker)來管理消息,消息代理會接收發送者發送的消息,并將其存儲起來,等待接收者來請求消息。
//發送者代碼 ConnectionFactory factory = new ActiveMQConnectionFactory("tcp://localhost:61616"); Connection connection = factory.createConnection(); Session session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE); Destination destination = session.createQueue("myQueue"); MessageProducer producer = session.createProducer(destination); TextMessage message = session.createTextMessage("Hello, World!"); producer.send(message); session.close(); connection.close(); //接收者代碼 ConnectionFactory factory = new ActiveMQConnectionFactory("tcp://localhost:61616"); Connection connection = factory.createConnection(); connection.start(); Session session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE); Destination destination = session.createQueue("myQueue"); MessageConsumer consumer = session.createConsumer(destination); TextMessage message = (TextMessage) consumer.receive(); System.out.println("Received message: " + message.getText()); session.close(); connection.close();
Socket編程允許Java程序建立網絡連接,實現網絡通訊。在Socket編程中,通訊的兩端都會有一個Socket對象,它們對應于網絡上的兩個端口。Java提供了ServerSocket和Socket兩個類,分別用于服務器端和客戶端的Socket對象創建。
//服務器端代碼 ServerSocket serverSocket = new ServerSocket(8080); System.out.println("Server started"); while (true) { Socket clientSocket = serverSocket.accept(); System.out.println("Client connected from " + clientSocket.getInetAddress().getHostAddress()); BufferedReader reader = new BufferedReader(new InputStreamReader(clientSocket.getInputStream())); BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(clientSocket.getOutputStream())); String line; while ((line = reader.readLine()) != null) { System.out.println("Received message: " + line); writer.write("Received: " + line); writer.newLine(); writer.flush(); } reader.close(); writer.close(); clientSocket.close(); } //客戶端代碼 Socket socket = new Socket("localhost", 8080); System.out.println("Connected to server"); BufferedReader reader = new BufferedReader(new InputStreamReader(socket.getInputStream())); BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(socket.getOutputStream())); writer.write("Hello, Server"); writer.newLine(); writer.flush(); String response = reader.readLine(); System.out.println("Received response: " + response); reader.close(); writer.close(); socket.close();