NodeJS 无法连接到WebSocket服务器

dwthyt8l  于 2023-08-04  发布在  Node.js
关注(0)|答案(1)|浏览(241)

我在我的主机上做了一个WebSocket服务器,<www.example.com>但是客户端没有连接到它。
代码如下:
Server.js:

const ws = new require('ws');
const wss = new ws.Server({noServer: true});
const http = require('http');
const express = require("express");
const app = express();
app.get("/multiplayerChat2/",(req,res) => {
    wss.handleUpgrade(req, req.socket, Buffer.alloc(0), onSocketConnect);
});
http.createServer(app).listen();
function onSocketConnect(ws){
    console.log("hello")
  ws.on('message', function(message) {
    message = message.slice(0, 50); // max message length will be 50
    wss.clients.forEach(function(client){
        client.send(message.toString("utf8"));  
    })
  });
}

字符串
客户端js:

let socket = new WebSocket("wss://example.com/multiplayerChat2/");
socket.onerror = (err) => {
  console.log("websocket error : ",err);
}
// send message from the form
document.forms.publish.onsubmit = function() {
  let outgoingMessage = this.message.value;
  socket.send(outgoingMessage);
  return false;
};

// message received - show the message in div#messages
socket.onmessage = function(event) {
  let message = event.data;

  let messageElem = document.createElement('div');
  messageElem.textContent = message;
  document.getElementById('messages').prepend(messageElem);
}


客户端html:

<!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>Document</title>
</head>
<body>
    <form name="publish">
        <input type="text" id="message">
        <input type="submit" value="Send">
    </form>
    <div id="messages"></div>
</body>
<script src="index.js"></script>
</html>


注意server.js文件在<example.com/multiplayerChat2>中。
我在WebSocket连接url上做了一些更改,但websocket连接给出了这个错误:

WebSocket connection to 'wss://example.com/multiplayerChat2/' failed:


编辑:好吧,我认为这是有点难,但至少说,我怎么能使一个WebSocket服务器不处理http请求,但其来源是在网站
编辑2:我改变了我的代码一点,我使用process.env.PORT,但它说端口已经使用(因为它的网站端口)我看到的地方,https的法律的端口是443和http是80,但我不能使用8080或80或443由于这个错误

qc6wkl3g

qc6wkl3g1#

你不能打开http服务器和连接wss:// .它需要是https,并指定证书的绝对路径。

var server
var is_ssl = true;
if (is_ssl) {
  var httpsOptions = {
    key: fs.readFileSync(process.env.SSL_KEY_FILE),
    cert: fs.readFileSync(process.env.SSL_CERT_FILE)
  };
  server = require('https').createServer(httpsOptions, app);
} else {
  server = require('http').createServer(app);
}

字符串

相关问题