简体   繁体   中英

WebSocket not connecting

I have a WebSocket server that I am trying to make and I can't figure out why it is not connecting.

index.html(client):

<p id="status">Connecting...</p>
<input id="message" />
<button id="submit">Send</button>
<script>
  var s = new WebSocket("wss://StarliteServer.cs641311.repl.run:8000", ["soap", "wamp"]);
  s.onopen = function() {
    document.getElementById("status").innerHTML="Connected";
  }
  document.getElementById("submit").addEventListener("click", function() {
    s.send(document.getElementById("message").value);
  });
  s.onmessage = function(e) {
    alert(e.data);
  }
  s.onclose = function(e) {
    document.getElementById("status").innerHTML = "ERROR: "+e.code
  }
</script>

app.js

var http = require('http');
http.createServer(function(req, res) {
  req.onopen = function() {
    console.log("OPENING CONNECTION");
    res.writeHead(200);
  }
  req.on('data', function(e) {
    res.write(e);
  });
  req.on('close', function() {
    console.log('CONNECTION CLOSED');
  });
}).listen(8000);

A websocket client requires a websocket server to connect to. While all webSocket connections do start with a plain http request, the server must then "upgrade" the connection to the webSocket protocol and the server must be able to speak that webSocket protocol. If not, the client will drop the connection since the server fails to support the proper protocol.

There are multiple websocket server libraries for node.js in NPM. Pick one of those and add it to your server. If your server intends to also serve as a regular http server, you can share the same http server with the websocket server. The webSocket server code will examine each incoming request and pick off the ones that show that they represent the initiation of a webSocket connection and it will take them over from there.

To give you an idea what a webSocket server must do, you can see this article on writing websocket servers . I'm not suggesting you write your own (too much time spent on protocol detail), but this will certainly explain why a plain http server won't suffice for a webSocket connection.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM