Implementation of message notification function written in Java
Introduction:
In software development, message notification is a common functional requirement, used to implement system Real-time notifications, push and other functions. As a powerful programming language, Java provides a rich class library and API, which can easily implement message notification functions. In this article, we will introduce how to use Java to write a simple message notification function and provide corresponding code examples.
Implementation ideas:
To implement the message notification function, there are two key parts: sending messages and receiving messages. In Java, you can use Socket or message queue to send and receive messages. Here we take the use of Socket to implement message notification as an example.
Steps:
Code example:
// MessageSender.java
import java.io.*;
import java.net.*;
public class MessageSender {
public static final int PORT = 1234; public static void main(String[] args) { try { ServerSocket serverSocket = new ServerSocket(PORT); System.out.println("Server started, waiting for client connection..."); Socket socket = serverSocket.accept(); System.out.println("Client connected."); BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); PrintWriter pw = new PrintWriter(socket.getOutputStream()); while (true) { String message = br.readLine(); // 从控制台读取消息 pw.println(message); // 发送消息给客户端 pw.flush(); if (message.equals("bye")) { break; } } br.close(); pw.close(); socket.close(); serverSocket.close(); } catch (IOException e) { e.printStackTrace(); } }
}
// MessageReceiver.java
import java.io.*;
import java.net.*;
public class MessageReceiver {
public static final String HOST = "localhost"; public static final int PORT = 1234; public static void main(String[] args) { try { Socket socket = new Socket(HOST, PORT); System.out.println("Connected to server."); BufferedReader br = new BufferedReader(new InputStreamReader(socket.getInputStream())); String message; while ((message = br.readLine()) != null) { System.out.println("Received message: " + message); if (message.equals("bye")) { break; } } br.close(); socket.close(); } catch (IOException e) { e.printStackTrace(); } }
}
Summary:
Writing message notification function in Java is very simple and flexible. By using Socket, we can send and receive messages. The above code example can be used as a basic framework, and the code can be modified and extended according to actual needs to implement more complex message notification functions.
The above is the detailed content of Implementation of message notification function written in Java. For more information, please follow other related articles on the PHP Chinese website!