无法连接到 WebSocket 服务器。

huangapple go评论107阅读模式
英文:

Cant connect to websocket server

问题

在我的主机中创建了一个WebSocket服务器,地址为<www.example.com>,但客户端无法连接。以下是代码:

Server.js:

const ws = 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(8080); // 使用8080端口

function onSocketConnect(ws) {
    console.log("hello");
    ws.on('message', function (message) {
        message = message.slice(0, 50); // 最大消息长度为50
        wss.clients.forEach(function (client) {
            client.send(message.toString("utf8"));
        });
    });
}

Client.js:

let socket = new WebSocket("wss://www.example.com/multiplayerChat2/");
socket.onerror = (err) => {
    console.log("websocket error: ", err);
};

// 从表单发送消息
document.forms.publish.onsubmit = function () {
    let outgoingMessage = this.message.value;
    socket.send(outgoingMessage);
    return false;
};

// 接收到消息 - 在div#messages中显示消息
socket.onmessage = function (event) {
    let message = event.data;

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

Client.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://www.example.com/multiplayerChat2/' failed:

编辑:好的,我认为这有点困难,但至少告诉我如何创建一个WebSocket服务器而不处理HTTP请求,但其来源在网站中。

编辑2:我稍微修改了代码并使用了process.env.PORT,但它说端口已被使用(因为它是网站的端口)。我在某处看到HTTPS的合法端口是443,HTTP的合法端口是80,但由于此错误,我无法使用8080、80或443。

英文:

I made a websocket server in my host in <www.example.com> but the client doesnt connect to it.
Here is the code :
Server.js :

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

Client js :

let socket = new WebSocket(&quot;wss://example.com/multiplayerChat2/&quot;);
socket.onerror = (err) =&gt; {
  console.log(&quot;websocket error : &quot;,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(&#39;div&#39;);
  messageElem.textContent = message;
  document.getElementById(&#39;messages&#39;).prepend(messageElem);
}

Client html :

&lt;!DOCTYPE html&gt;
&lt;html lang=&quot;en&quot;&gt;
&lt;head&gt;
    &lt;meta charset=&quot;UTF-8&quot;&gt;
    &lt;meta http-equiv=&quot;X-UA-Compatible&quot; content=&quot;IE=edge&quot;&gt;
    &lt;meta name=&quot;viewport&quot; content=&quot;width=device-width, initial-scale=1.0&quot;&gt;
    &lt;title&gt;Document&lt;/title&gt;
&lt;/head&gt;
&lt;body&gt;
    &lt;form name=&quot;publish&quot;&gt;
        &lt;input type=&quot;text&quot; id=&quot;message&quot;&gt;
        &lt;input type=&quot;submit&quot; value=&quot;Send&quot;&gt;
    &lt;/form&gt;
    &lt;div id=&quot;messages&quot;&gt;&lt;/div&gt;
&lt;/body&gt;
&lt;script src=&quot;index.js&quot;&gt;&lt;/script&gt;
&lt;/html&gt;

Note that the server.js file is in <example.com/multiplayerChat2>.
I made some changes on the websocket connection url but websocket connection gives this error :

WebSocket connection to &#39;wss://example.com/multiplayerChat2/&#39; failed: 

EDIT : ok i think this is a little bit hard but at least say how can i make a websocket server without handling http requests but its origin be in the website

EDIT 2 : I changed my code a little and i used process.env.PORT but it says the port is already used(because its the port of the website) i saw somewhere that the legal port for https is 443 and for http is 80 but i couldnt use 8080 or 80 or 443 due to this error

答案1

得分: 0

你不能打开 `http` 服务器并连接到 `wss://` 必须使用 `https`并指定证书的绝对路径
```js
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);
}
英文:

you can't open http server and connect with wss://. it needs to be https with specifying the absolute path of the certificate.

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(&#39;https&#39;).createServer(httpsOptions, app);
} else {
  server = require(&#39;http&#39;).createServer(app);
}

huangapple
  • 本文由 发表于 2023年7月23日 21:45:32
  • 转载请务必保留本文链接:https://go.coder-hub.com/76748567.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定