当前位置:网站首页>Simple use of websocket
Simple use of websocket
2022-07-07 14:23:00 【LLAiden】
Introduce
WebSocket It's one in a single TCP Connect to carry on full duplex Communication protocol .WebSocket The communication protocol is 2011 By the IETF Set it as a standard RFC 6455, And by the RFC7936 Supplementary specifications .WebSocket API Also by W3C Set it as a standard .
WebSocket Makes it easier to exchange data between client and server , Allows the server to actively push data to the client . stay WebSocket API in , The browser and the server only need to complete a handshake , A persistent connection can be created directly between the two , And two-way data transmission
After the introduction, go directly to the code
Server side
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();
}
}
client
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 Version client
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);
}
Running effect
Code address : https://github.com/LLAiden/webSocketDemo
Using open source libraries in code : 'org.java-websocket:Java-WebSocket:1.5.2'
Open source library address : https://github.com/TooTallNate/Java-WebSockethttps://github.com/TooTallNate/Java-WebSocket
边栏推荐
- Multi merchant mall system function disassembly lecture 01 - Product Architecture
- SAKT方法部分介绍
- Navigation — 这么好用的导航框架你确定不来看看?
- 2022PAGC 金帆奖 | 融云荣膺「年度杰出产品技术服务商」
- 手里的闲钱是炒股票还是买理财产品好?
- oracle 触发器实现级联更新
- Attribute keywords aliases, calculated, cardinality, ClientName
- 用例图
- requires php ~7.1 -> your PHP version (7.0.18) does not satisfy that requirement
- LeetCode 648. Word replacement
猜你喜欢
Equipment failure prediction machine failure early warning mechanical equipment vibration monitoring machine failure early warning CNC vibration wireless monitoring equipment abnormal early warning
Selenium库
最长上升子序列模型 AcWing 1012. 友好城市
AutoCAD - how to input angle dimensions and CAD diameter symbols greater than 180 degrees?
js 获取当前时间 年月日,uniapp定位 小程序打开地图选择地点
Details of redis core data structure & new features of redis 6
VSCode 配置使用 PyLint 语法检查器
常用數字信號編碼之反向不歸零碼碼、曼徹斯特編碼、差分曼徹斯特編碼
STM32CubeMX,68套组件,遵循10条开源协议
The longest ascending subsequence model acwing 482 Chorus formation
随机推荐
搜索框效果的实现【每日一题】
PERT图(工程网络图)
3D detection: fast visualization of 3D box and point cloud
Flask session forged hctf admin
[AI practice] Application xgboost Xgbregressor builds air quality prediction model (II)
Oracle Linux 9.0 正式发布
Huawei image address
LeetCode每日一题(636. Exclusive Time of Functions)
请问,在使用flink sql sink数据到kafka的时候出现执行成功,但是kafka里面没有数
【立体匹配论文阅读】【三】INTS
一个简单LEGv8处理器的Verilog实现【四】【单周期实现基础知识及模块设计讲解】
ARM Cortex-A9,MCIMX6U7CVM08AD 处理器应用
Bashrc and profile
请问,如图,pyhon云函数提示使用了 pymysql模块,这个是怎么回事?
Realization of search box effect [daily question]
Seven propagation behaviors of transactions
Substance Painter笔记:多显示器且多分辨率显示器时的设置
杭电oj2092 整数解
通过 iValueConverter 给datagrid 的背景颜色 动态赋值
IP address home location query