webSocket前台实现
简单实现:
<!DOCTYPE html>
<html lang="en"> <head> <meta charset="UTF-8"> <title>Title</title> <script type="application/javascript" src="js/base64.js"></script> <script> var wsUri="ws:127.0.0.1:20000"; var output; function init(e){ output=document.getElementById("output"); testWebSocket(); } function testWebSocket(){ websocket=new WebSocket(wsUri); //与服务器连接成功 websocket.onopen=function(evt){ onOpen(evt); } //服务器端关闭 websocket.onclose = function(evt) { onClose(evt) }; //接受传过来的数据 websocket.onmessage = function(evt) { onMessage(evt) }; //发送失败错误提示 websocket.onerror = function(evt) { onError(evt) }; } function onOpen(evt){ document.getElementById("output").value="[user:127.0.0.1]#"; doSend("WebSocket rocks"); } function onClose(evt) { writeToScreen("DISCONNECTED"); }function onMessage(evt) {
// var b=new Base64(); // alert(b.decode(evt.data)); writeToScreen('<span style="color: blue;">RESPONSE: '+ evt.data+'</span>'); }function onError(evt) {
writeToScreen('<span style="color: red;">ERROR:</span> '+ evt.data); }function doSend(message) {
if(websocket.readyState==1){ alert("连接成功"); websocket.send(message); setTimeout(function(){ if(websocket.readyState==1){ alert("无需尝试发送!"); }else{ alert("尝试发送"); doSend(message); } },1000); }}
function writeToScreen(message){ var pre=document.createElement("p"); pre.style.wordWrap="break-word"; pre.innerHTML=message; } document.οnkeydοwn=function(e){ var keycode=e.keyCode; if(keycode==13){ doSend(document.getElementById("output").value); } } window.addEventListener("load",init,false); </script> </head> <body> </body> <h2>WebSocket Test</h2> <input id="output" style="width: 300px;height: 100px;background: black;color: whitesmoke;"></input> </html> vertx后台监听简单实现: Vertx vertx=Vertx.vertx(); vertx.createHttpServer().websocketHandler(res->{ ServerWebSocket server=res.resume(); server.handler(v->{ System.out.println(v); }); server.write(Buffer.buffer("HTTP/1.1 101 Switching Protocols\nUpgrade: websocket\nConnection:Upgrade\nSec-WebSocket-Accept:izP3aDUEV5674E3AhIay4m1jU1c=\n\n\n".getBytes())); System.out.println(server.path()); server.writeTextMessage("123"); }).listen(20000,res->{ if(res.succeeded()){ System.out.println("success"); }else{ System.out.println("fail"); } }); --------------------- 作者:WX5991 来源:CSDN 原文:https://blog.csdn.net/WX5991/article/details/79108316 版权声明:本文为博主原创文章,转载请附上博文链接!