websocket通信案例

HTML5 WebSocket

菜鸟教程

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta http-equiv="X-UA-Compatible" content="IE=edge">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>websocket通信dome</title>
  <style>
    .main{
      position: absolute;
      top: 50%;
      left: 50%;
      transform: translate(-50%, -50%);
      background-color: cornsilk;
      padding: 30px;
      padding: 30px;
    }
    .top{
      width: 400px;
      padding: 30px;
      background-color: burlywood;
    }
    .bottom{
      width: 400px;
      background-color: cadetblue;
      padding: 30px;
    }
  </style>
</head>
<body>
  <div class="main">
    <div class="top">
      <div style="padding-bottom: 20px;">
        <span>输入内容:</span>
        <input type="text" id="sendText">
      </div>
      <div>
        <button id="send">发送</button>
        &emsp;
        &emsp;
        &emsp;
        <button id="reset">重置</button>
      </div>
    </div>
    <div class="bottom">
      <textarea name="" id="text" cols="50" rows="30"></textarea>
    </div>
  </div>
</body>
<script>
  var ws = null; //WebSocket 链接
  var url = "ws://127.0.0.1:9999"; //本地node运行的服务器  ip地址加端口号
  // 本地node运行服务器的命令(需要在node文件下运行黑窗口) : node webSocket.js

  var send = document.getElementById('send'); //发送按钮
  var reset = document.getElementById('reset'); //重置按钮
  var textaa = document.getElementById('text'); //显示文本的框
  var sendText = document.getElementById('sendText'); //需要发送的文本


  function open(){ //打开链接
    if("WebSocket" in window){ //检查当前浏览器是否支持websocket
      if(ws){ //判断是否已链接
        ws.close();
        ws = null;
      }
      //打开一个websocket
      ws = new WebSocket(url);
      ws.onopen = function(evt){
        sendMain(); //执行发送指令
      };
      ws.onmessage = function (evt){ //接收到信息--把信息添加到接收记录中并关闭链接
        console.log('信息--',evt)
        textaa.value = textaa.value+"\n "+evt.data;
        send.disabled = false;
        ws.close();
        ws = null;
      }
    }else{
      textaa.value = textaa.value+"\n 您的浏览器不支持WebSocket";
    }
  }

  function sendMain(){  //发送数据
    send.disabled = true; //先禁用按钮,防止连续触发造成链接错误
    ws.send(sendText.value); //使用连接发送数据
  }

  function resetMain(){ //重置链接
    if(ws){
      ws.close(); //关闭通信
      ws = null;
    }
    textaa.value = textaa.value + "\n 重置链接成功";
    send.disabled = false;
  }

  send.onclick = function () { open(); }
  reset.onclick = function () { resetMain(); }
</script>
</html>

效果

websocket通信案例_第1张图片

你可能感兴趣的:(websocket,javascript,前端)