将Websocket与xampp

时间:2019-02-27 05:20:32

标签: javascript websocket

我试图将Websocket与xampp服务器一起使用。我从教程的角度开始关注该教程。我得到的错误是javascript错误: client.js:55 WebSocket连接到'ws:// localhost:9090 /'失败:连接建立错误:net :: ERR_CONNECTION_REFUSED

这是我的代码 index.html

<html lang = "en"> 
   <head> 
      <meta charset = "utf-8" /> 
   </head>

   <body> 

      <div> 
         <input type = "text" id = "loginInput" /> 
         <button id = "loginBtn">Login</button> 
      </div> 

      <div> 
         <input type = "text" id = "otherUsernameInput" />
         <button id = "connectToOtherUsernameBtn">Establish connection</button> 
      </div> 

      <script src = "client.js"></script>

   </body>

</html>

client.js

var connection = new WebSocket('ws://localhost:9090'); 
var name = ""; 

var loginInput = document.querySelector('#loginInput'); 
var loginBtn = document.querySelector('#loginBtn'); 
var otherUsernameInput = document.querySelector('#otherUsernameInput'); 
var connectToOtherUsernameBtn = document.querySelector('#connectToOtherUsernameBtn'); 
var connectedUser, myConnection;

//when a user clicks the login button 
loginBtn.addEventListener("click", function(event){ 
   name = loginInput.value; 

   if(name.length > 0){ 
      send({ 
         type: "login", 
         name: name 
      }); 
   } 

});

//handle messages from the server 
connection.onmessage = function (message) { 
   console.log("Got message", message.data);
   var data = JSON.parse(message.data); 

   switch(data.type) { 
      case "login": 
         onLogin(data.success); 
         break; 
      case "offer": 
         onOffer(data.offer, data.name); 
         break; 
      case "answer": 
         onAnswer(data.answer); 
         break; 
      case "candidate": 
         onCandidate(data.candidate); 
         break; 
      default: 
         break; 
   } 
};

//when a user logs in 
function onLogin(success) { 

   if (success === false) { 
      alert("oops...try a different username"); 
   } else { 
      //creating our RTCPeerConnection object 

      var configuration = { 
         "iceServers": [{ "url": "stun:stun.1.google.com:19302" }] 
      }; 

      myConnection = new webkitRTCPeerConnection(configuration); 
      console.log("RTCPeerConnection object was created"); 
      console.log(myConnection); 

      //setup ice handling
      //when the browser finds an ice candidate we send it to another peer 
      myConnection.onicecandidate = function (event) { 

         if (event.candidate) { 
            send({ 
               type: "candidate", 
               candidate: event.candidate 
            }); 
         } 
      }; 
   } 
};

connection.onopen = function () { 
   console.log("Connected"); 
};

connection.onerror = function (err) { 
   console.log("Got error", err); 
};

// Alias for sending messages in JSON format 
function send(message) { 

   if (connectedUser) { 
      message.name = connectedUser; 
   } 

   connection.send(JSON.stringify(message)); 
};

0 个答案:

没有答案