要实现服务端主动向客户端发送消息,主要有以下方法:
- 服务端使用Socket的getOutputStream()获取输出流,写入消息:
// 服务端
ServerSocket server = new ServerSocket(8000);
Socket socket = server.accept();
OutputStream out = socket.getOutputStream();
out.write("Hello".getBytes());
- 服务端定期向客户端发送消息,使用线程实现:
// 服务端
ServerSocket server = new ServerSocket(8000);
Socket socket = server.accept();
new Thread() {
public void run() {
OutputStream out = socket.getOutputStream();
while (true) {
out.write("Hello".getBytes());
try {
Thread.sleep(1000); // 1s发送一次
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}.start();
- 客户端读取服务端发送的消息:
// 客户端
Socket socket = new Socket("127.0.0.1", 8000);
InputStream in = socket.getInputStream();
byte[] buffer = new byte[1024];
while (true) {
int len = in.read(buffer);
if (len != -1) {
String msg = new String(buffer, 0, len);
System.out.println(msg); // 打印服务端发送的消息
}
}
- 服务端使用DatagramSocket发送UDP消息:
// 服务端
DatagramSocket socket = new DatagramSocket();
while (true) {
byte[] data = "Hello".getBytes();
InetSocketAddress address = new InetSocketAddress("127.0.0.1", 8000);
DatagramPacket packet = new DatagramPacket(data, data.length, address);
socket.send(packet); // 发送UDP消息
}
- 客户端使用DatagramSocket接收UDP消息:
// 客户端
DatagramSocket socket = new DatagramSocket(8000);
byte[] buffer = new byte[1024];
while (true) {
DatagramPacket packet = new DatagramPacket(buffer, buffer.length);
socket.receive(packet); // 接收UDP消息
String msg = new String(packet.getData(), 0, packet.getLength());
System.out.println(msg);
}