webSocket无法正常工作

时间:2017-10-24 03:50:37

标签: node.js websocket

我是webSocket的新手。我用webSocket创建了一个示例代码为

的示例

server.js

var WebSocketServer = require('ws').Server;

var PORT = 8000;

// var wss = new WebSocketServer({port: PORT});
var wss=new WebSocketServer({port:PORT});
console.log('welcome ');
 var messages = [];
wss.on('connection', function (ws) {
 messages.forEach(function(message){
  console.log('enter into the connection');
ws.send(message);
});
ws.on('message', function (message) {
messages.push(message);
console.log('Message Received: %s', message);
wss.clients.forEach(function (conn) {
  conn.send(message);
});
});
});

的index.html

<!DOCTYPE html>
<html>
 <head>
<title>Chat Client</title>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<style>
  #chatBox{width: 100%;height: 80%; position: absolute; top: 0; overflow: 
  scroll;}
  #messageForm{width: 100%; height: 20%; position: absolute; bottom: 0;}
  html body{width: 100%; height: 100%}
  </style>
  <script>
  var url = "ws://localhost:8000/";
  var user;
  var socket;
  function connectToChat() {
    socket = new WebSocket(url);
    user = document.getElementById("name").value;
    socket.onmessage = function (msg) {
      var chatBox = document.getElementById("chatBox");
      var message = JSON.parse(msg.data);
      chatBox.innerHTML = "<b>" + message.user + "</b>:" + message.text + "
     <br>" + chatBox.innerHTML;
    };
    socket.onopen = function () {
      var message = {};
      message.user = user;
      message.text = "<b>Joined the chat</b>";
      socket.send(JSON.stringify(message));
    };
    document.getElementById("chat").setAttribute("style", "");
    document.getElementById("welcome").setAttribute("style", 
 "display:none");
  }
  function sendMessage() {
    var message = {};
    message.user = user;
    message.text = document.getElementById("message").value;
    socket.send(JSON.stringify(message));
    document.getElementById("message").value = "";
  }
  window.onload = function () {
    document.getElementById("chat").setAttribute("style", "display:none");
  }
  </script>
  </head>
 <body>
 <div id="welcome">
  <h1>WebSocket Chat</h1>
  What is your name? 
  <input type="text" id="name">
  <input type="button" value="Join Chat" onclick="connectToChat();">
  </div>
  <div id="chat">
  <div id="chatBox">

  </div>
  <div id="messageForm">
    <input type="text" id="message">
    <input type="button" value="send" onclick="sendMessage();">
    </div>
    </div>
  </body>
 </html>

我收到了错误    无法加载资源:服务器响应状态为426(升级    必需的)

上面的代码有什么问题。我正在使用“ws”版本3.2.0和node.js 6.10以及google chrome也是新版本。请帮帮我

0 个答案:

没有答案