介绍
WebSocket是一种在单个TCP连接上进行全双工通信的协议。WebSocket通信协议于2011年被IETF定为标准RFC 6455,并由RFC7936补充规范。WebSocket API也被W3C定为标准。
WebSocket使得客户端和服务器之间的数据交换变得更加简单,允许服务端主动向客户端推送数据。在WebSocket API中,浏览器和服务器只需要完成一次握手,两者之间就直接可以创建持久性的连接,并进行双向数据传输
介绍完直接上代码
服务端
public class WebSocketServerDemo {
static SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
public static void main(String[] args) {
WebSocketServer webSocketServer = new WebSocketServer() {
@Override
public void onOpen(WebSocket conn, ClientHandshake handshake) {
System.out.println("welcome webSocket...");
}
@Override
public void onClose(WebSocket conn, int code, String reason, boolean remote) {
System.out.println("close webSocket...");
}
@Override
public void onMessage(WebSocket conn, String message) {
System.out.println("received client message: " + message);
conn.send(simpleDateFormat.format(new Date()));
}
@Override
public void onError(WebSocket conn, Exception ex) {
ex.printStackTrace();
}
@Override
public void onStart() {
System.out.println("websocket start");
}
};
webSocketServer.start();
}
}
客户端
public class WebSocketClientDemo {
public static void main(String[] args) throws URISyntaxException {
WebSocketClient webSocketClient = new WebSocketClient(new URI("ws://localhost:80")) {
@Override
public void onOpen(ServerHandshake handshakedata) {
String httpStatusMessage = handshakedata.getHttpStatusMessage();
System.out.println("httpStatusMessage: " + httpStatusMessage);
}
@Override
public void onMessage(String message) {
System.out.println("received server message: " + message);
}
@Override
public void onClose(int code, String reason, boolean remote) {
System.out.println("close code: " + code);
System.out.println("close reason: " + reason);
System.out.println("close remote: " + remote);
}
@Override
public void onError(Exception ex) {
ex.printStackTrace();
}
};
webSocketClient.connect();
Timer timer = new Timer();
timer.schedule(new TimerTask() {
int count = 0;
@Override
public void run() {
if (webSocketClient.isOpen()) {
webSocketClient.send(String.valueOf(count++));
}
}
}, 1000, 1000);
}
okhttp版客户端
OkHttpClient okHttpClient = new OkHttpClient.Builder().build();
Request request = new Request.Builder()
.url("ws://localhost:80")
.get()
.build();
WebSocket webSocket = okHttpClient.newWebSocket(request, new WebSocketListener() {
@Override
public void onFailure(@NotNull WebSocket webSocket, @NotNull Throwable t, @Nullable Response response) {
t.printStackTrace();
}
@Override
public void onMessage(@NotNull WebSocket webSocket, @NotNull String text) {
System.out.println("received server message: " + text);
}
@Override
public void onMessage(@NotNull WebSocket webSocket, @NotNull ByteString bytes) {
String text = bytes.base64();
System.out.println("received server message: " + text);
}
@Override
public void onOpen(@NotNull WebSocket webSocket, @NotNull Response response) {
System.out.println(response);
}
});
Timer timer = new Timer();
timer.schedule(new TimerTask() {
int count = 0;
@Override
public void run() {
webSocket.send(String.valueOf(count++));
}
}, 1000, 1000);
}
运行效果
代码地址: https://github.com/LLAiden/webSocketDemo
代码中使用开源库: 'org.java-websocket:Java-WebSocket:1.5.2'
开源库地址: https://github.com/TooTallNate/Java-WebSockethttps://github.com/TooTallNate/Java-WebSocket