test.html 2.81 KB
<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>WebSocket test</title>
  <style>
    p { padding: 0; margin: 0; }
    .container{ margin: 10vh auto; width: 40%; border: 1px solid #ffeeaa; padding: 10px; }
    #output { max-height: 500px; margin-bottom: 10px; overflow-y: auto; }
    .message-wrapper { width: 100%; overflow: hidden; }
    .message-wrapper input { float: left; width: 90%; padding: 4px 12px; box-sizing: border-box; }
    .message-wrapper button { float: right; padding: 4px 10px; }
  </style>
</head>
<body>
  <div class="container">
    <div id="output"></div>
    <div class="message-wrapper">
      <input type="text" id="msg" />
      <button id="sendBtn">发 送</button>
    </div>
  </div>
  <script src="./js/socket.js"></script>
  <script>
    if (!window.WebSocket) {
      //
    }
    var socket = new ws('ws://123.207.136.134:9010/ajaxchattest'),
      str = 'Hello WebSocket!!';

    socket.onconnecting = function (ev) {
      console.log('socket:onconnecting', ev)
      sendMsg('socket test...')
    }
    socket.onopen = function(ev) {
      console.log('socket:onopen', ev)
      log('发了个消息!' + str)
      sendMsg(str)
    }
    socket.onclose = function(ev) {
      console.log('socket:onclose', ev)
      log('WebSocket Closed!!')
    }
    socket.onmessage = function(ev) {
      console.log('socket:onmessage', ev)
      log('收到消息 ' + ev.data)
      // socket.close()
    }

    var sendBtn = document.getElementById('sendBtn'),
      msgInput = document.getElementById('msg');

    sendBtn.onclick = onBtnClick

    function onBtnClick() {
      var val = msgInput.value.trim();
      if (!val) return
      sendMsg(val)
      msgInput.value = ''
    }

    document.addEventListener('keydown', function(ev) {
      var e = ev || window.event;
      if (e.keyCode === 13) {
        onBtnClick()
      }
    })

    function sendMsg(str) {
      console.log('socket:sendMsg', str)
      socket.send(str)
    }

    var timer = null
    function log(s, e) {
      var output = document.getElementById('output'),
        p = document.createElement('p');

      clearTimeout(timer);
      timer = null

      p.style.wordWrap = 'break-word';
      p.style.padding = '10px';
      p.style.marginBottom = '4px';
      p.style.background = '#eee';
      p.textContent = 'LOG : ' + s;
      // 往上追加
      // output.childNodes.length
      //   ? output.insertBefore(p, output.childNodes[0])
      //   : output.appendChild(p);
      // 往下追加
      output.appendChild(p);
      if (output.offsetWidth !== output.scrollWidth) {
        console.log('timer', timer)
        output.scrollTop = output.scrollHeight
        timer = setTimeout(function() {
        }, 100)
      }
    }
  </script>
</body>
</html>