为了发送WebSocket消息,无论注解式端点还是编程式端点,其API都是相同的:RemoteEndpoint和它的子类(RemoteEndpoint.Basic和RemoteEndpoint.Async)提供了发送消息的所有方法。
Ping和Pong消息通常被开发人员用来检查WebSocket底层连接的健康性。
从Session对象获得的RemoteEndpoint实例提供方法:
public void sendPing(ByteBuffer applicationData) throws IOException, IllegalArgumentException;
public void sendPong(ByteBuffer applicationData) throws IOException, IllegalArgumentException;
- WebSocket规范定义了Ping和Pong消息可以传输125个字节大小的二进制数据
- 调用这些方法时,如果传入的ByteBuffer参数超过了125个字节,则会抛出IllegalArgumentException异常
- RemoteEndpoint接口和它的派生类中的所有发送消息的方法都会通过抛出IOException异常来表明在消息的传输过程中出现了错误
1. 发送消息
同步发送 RemoteEndpoint.Basic接口
1.1 发送字符串消息
//发送文本消息
public void sendText(String text) throws IOException;
//使用Writter API发送String消息
public Writter getSendStream() throws IOException;
//以分片的方式发送文本消息
public void sendText(String partialMessage, boolean isLast) throws IOException;
1.2 发送二进制消息
//发送二进制消息
public void sendBinary(ByteBuffer data) throws IOException;
//分片发送二进制消息
public void sendBinary(ByteBuffer partialByte, boolean isLast) throws IOException;
//使用流发送二进制消息
public Outputstream getSendStream() throws IOException;
1.3 发送对象消息
//发送Java对象消息
public void sendObject(Object data) throws IOException, EncodeException;
Websocket是如何实现把对象编程WebSocket消息的,答案取决于你传什么类型的对象
- 如果你传一个Java基本类型对象(或者其等值装箱类),则WebSocket实现会把数据转换成一个标准的Java字符串对象(使用toString()方法)
- 如果传入的是其他对象,那么要为WebSocket实现提供一个javax.websocket.Encoder接口的实现
public String encode(T object) throws EncodeException;
public class DrawingEncoder implements Encoder.Text<DrawingObject> {
@Override
public String encode(DrawingObject drawingObject) throws EncodeException {
...