WebSocketVerticle.java
只是一个简单的demo,可以主动从服务端推送到js端。 直接运行 Main方法即可。
import com.xiaoniu.im.utils.Runner;
import io.vertx.core.AbstractVerticle;
import io.vertx.core.http.ServerWebSocket;
import java.time.LocalDateTime;
import java.util.HashMap;
import java.util.Map;
/**
* Created by sweet on 2017/9/27.
*/
public class WebSocketVerticle extends AbstractVerticle {
public static void main(String[] args) {
Runner.runExample(WebSocketVerticle.class);
}
private Map<String, ServerWebSocket> localMap;
@Override
public void start() throws Exception {
localMap = new HashMap<>();
vertx.createHttpServer().websocketHandler(serverWebSocket -> {
String path = serverWebSocket.path();
if (path.equals("/myapp")) {
serverWebSocket.handler(buffer -> {
String id = serverWebSocket.textHandlerID();
localMap.put(id, serverWebSocket);
System.out.println("--------------------");
System.out.println("server收到消息: " + buffer.toString());
System.out.println("--------------------");
serverWebSocket.writeTextMessage("我是服务器,我收到你的消息了 " + LocalDateTime.now());
});
} else {
serverWebSocket.reject(); // 拒绝连接
}
serverWebSocket.closeHandler(c -> {
System.out.println("socket 关闭了");
});
serverWebSocket.endHandler(end -> {
System.out.println("end 操作");
});
serverWebSocket.exceptionHandler(ex -> {
ex.printStackTrace();
});
}).listen(8080, server -> {
if (server.succeeded()) {
System.out.println("启动成功");
} else {
server.cause().printStackTrace();
}
});
// 模拟全局推送消息 30秒后
vertx.setTimer(30000, timer -> {
System.out.println("时间到了, map size " + localMap.size());
localMap.forEach((k, v) -> {
System.out.println("定时任务触发");
System.out.println("id: " + k);
ServerWebSocket serverWebSocket = v;
serverWebSocket.writeTextMessage("我是服务器,这是定时任务发送的消息 " + LocalDateTime.now());
serverWebSocket.close(); // 自己决定什么时候关闭
});
});
}
}
复制代码
index.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
</head>
<body>
<script>
var socket;
if (window.WebSocket) {
socket = new WebSocket("ws://localhost:8080/myapp");
socket.onmessage = function (event) {
alert("data from websocket: " + event.data);
};
socket.onopen = function (event) {
alert("Web Socket 打开!");
};
socket.onclose = function (event) {
console.log("Web Socket 关闭.");
};
} else {
alert("Your browser does not support Websockets. (Use Chrome)");
}
function send(message) {
if (!window.WebSocket) {
return;
}
if (socket.readyState == WebSocket.OPEN) {
socket.send(message);
} else {
alert("The socket is not open.");
}
}
</script>
<form onsubmit="return false;">
<input type="text" name="message" value="Hello, World!"/>
<input type="button" value="Send Web Socket Data" onclick="send(this.form.message.value)"/>
</form>
</body>
</html>
复制代码
Runner.java
https://github.com/vert-x3/vertx-examples/blob/master/core-examples/src/main/java/io/vertx/example/util/Runner.java